#!/bin/sh
# Startet den smartschankConfigurator (SSC) unter Wine.
#
# Beim ersten Start bekommt jeder Benutzer einen eigenen Wine-Prefix mit Wine-Mono (statt
# Microsoft .NET) und das SSC wird still hineininstalliert. Liefert das Paket später eine
# andere SSC-Version mit, wird sie beim nächsten Start nachinstalliert. Der SSC-eigene
# Updater installiert ebenfalls in den Prefix.
set -u

LIB="${SSC_LIB:-/usr/lib/smartschank-ssc}"
SSC_MSI="$LIB/smartschankConfigurator.msi"
MONO_MSI=$(ls "$LIB"/wine-mono-*-x86.msi 2>/dev/null | head -n 1)
BUNDLED_VERSION=$(cat "$LIB/ssc-version")

export WINEPREFIX="${SSC_WINEPREFIX:-${XDG_DATA_HOME:-$HOME/.local/share}/smartschank-ssc}"
export WINEDEBUG="${WINEDEBUG:--all}"
# Keine Wine-eigenen Menüeinträge und Dateizuordnungen im Linux-Desktop anlegen
export WINEDLLOVERRIDES="winemenubuilder.exe=d"

APP='C:\Program Files (x86)\Dirmeier Schanktechnik GmbH & Co KG\smartschankConfigurator\smartschank.exe'
APP_UNIX="$WINEPREFIX/drive_c/Program Files (x86)/Dirmeier Schanktechnik GmbH & Co KG/smartschankConfigurator/smartschank.exe"
STAMP="$WINEPREFIX/.ssc-paket-version"
LOG="$WINEPREFIX/einrichtung.log"

meldung() {
    if command -v notify-send >/dev/null 2>&1; then
        notify-send -a smartschankConfigurator -i smartschank-ssc "smartschankConfigurator" "$1"
    fi
    echo "$1" >&2
}

fehler() {
    if command -v zenity >/dev/null 2>&1; then
        zenity --error --title=smartschankConfigurator --text="$1" 2>/dev/null
    else
        meldung "$1"
    fi
    exit 1
}

if [ ! -f "$WINEPREFIX/system.reg" ]; then
    meldung "Erster Start: das SSC wird eingerichtet, das dauert etwa 20 Sekunden."
    mkdir -p "$WINEPREFIX"
    # mscoree/mshtml aus, sonst fragt wineboot per Dialog nach dem Download von Mono und Gecko.
    # Mono kommt gleich aus dem Paket, Gecko braucht das SSC nicht.
    WINEDLLOVERRIDES="$WINEDLLOVERRIDES;mscoree,mshtml=" wine wineboot -i >>"$LOG" 2>&1
fi

if [ ! -d "$WINEPREFIX/drive_c/windows/mono" ]; then
    wine msiexec /i "$MONO_MSI" /qn >>"$LOG" 2>&1
fi

if [ "$(cat "$STAMP" 2>/dev/null)" != "$BUNDLED_VERSION" ]; then
    # Ist per SSC-Updater schon eine neuere Version drin, bricht die MSI still ab - das ist gewollt.
    wine msiexec /i "$SSC_MSI" /qn >>"$LOG" 2>&1
    [ -f "$APP_UNIX" ] && echo "$BUNDLED_VERSION" >"$STAMP"
fi

[ -f "$APP_UNIX" ] || fehler "Das SSC konnte nicht eingerichtet werden. Details: $LOG"

cd "$(dirname "$APP_UNIX")" || exit 1
exec wine "$APP"
