#!/usr/bin/env bash
set -Eeuo pipefail

operation=${1:-}
if [[ "$operation" = check ]]; then
    if ! dpkg-query -W -f='${Status}\n' wine32:i386 2>/dev/null | \
        grep -Fx 'install ok installed' >/dev/null; then
        printf '%s\n' \
            'ECZ Windows mist de 32-bit compatibiliteitsruntime.' \
            'Voer als beheerder scripts/enable-windows-runtime-vm.sh uit.' >&2
        exit 69
    fi
    wine --version
    exit 0
fi

prefix=${2:-}
[[ -n "$operation" && -n "$prefix" && "$prefix" = /* ]] || {
    printf 'Invalid ECZ Windows runtime request.\n' >&2
    exit 2
}
shift 2

export WINEPREFIX="$prefix"
export WINEDEBUG=-all
export WINEDLLOVERRIDES="${WINEDLLOVERRIDES:+$WINEDLLOVERRIDES;}winemenubuilder.exe=d"

case "$operation" in
    initialize|repair)
        [[ $# -eq 0 ]] || exit 2
        mkdir -p "$prefix"
        cd "$prefix"
        exec wineboot -u
        ;;
    execute)
        [[ $# -ge 1 ]] || exit 2
        cd "$prefix/drive_c"
        exec wine "$@"
        ;;
    execute-from)
        [[ $# -ge 2 ]] || exit 2
        working_directory=$1
        shift
        canonical_working_directory=$(realpath -e -- "$working_directory")
        [[ -d "$canonical_working_directory" && \
            "$canonical_working_directory" = "$prefix/drive_c/"* ]] || {
            printf 'Unsafe Windows working directory.\n' >&2
            exit 1
        }
        cd "$canonical_working_directory"
        exec wine "$@"
        ;;
    execute-link)
        [[ $# -eq 1 ]] || exit 2
        shortcut=$1
        [[ "$shortcut" = "$prefix/drive_c/"* ]] || {
            printf 'Unsafe Windows shortcut path.\n' >&2
            exit 1
        }
        relative=${shortcut#"$prefix/drive_c/"}
        windows_shortcut="C:\\${relative//\//\\}"
        cd "$prefix/drive_c"
        exec wine start "$windows_shortcut"
        ;;
    install-msi)
        [[ $# -eq 1 ]] || exit 2
        cd "$prefix/drive_c"
        exec wine msiexec /i "$1"
        ;;
    set-version)
        [[ $# -eq 1 ]] || exit 2
        case "$1" in
            winxp|win7|win8|win81|win10|win11) ;;
            *) printf 'Unsupported Windows compatibility version.\n' >&2; exit 2 ;;
        esac
        cd "$prefix/drive_c"
        exec winecfg -v "$1"
        ;;
    tool)
        [[ $# -eq 1 ]] || exit 2
        cd "$prefix/drive_c"
        case "$1" in
            winecfg) exec winecfg ;;
            control) exec wine control ;;
            regedit) exec wine regedit ;;
            taskmgr) exec wine taskmgr ;;
            uninstaller) exec wine uninstaller ;;
            explorer) exec wine explorer ;;
            cmd) exec wine cmd ;;
            *) printf 'Unknown Windows configuration tool.\n' >&2; exit 2 ;;
        esac
        ;;
    *)
        printf 'Unknown ECZ Windows runtime operation.\n' >&2
        exit 2
        ;;
esac
