#!/bin/sh
# ============================================================================
# SPDX-License-Identifier: GPL-3.0-or-later
# Arcanum: Of Steamworks and Magick Obscura — Native 64-Bit Port (arcport)
# Installer Backend (invoked by Graphical Setup Wizard or CLI --cli)
# Packaged by tools/make-release.sh; ships zero game data (LEGAL.md §5).
# ============================================================================
set -eu

PKG_DIR=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P)
ARC_VERSION=$(awk 'NR==1{print $1}' "$PKG_DIR/VERSION" 2>/dev/null || true)
[ -n "$ARC_VERSION" ] || ARC_VERSION="unknown"
INSTALL_ROOT="${XDG_DATA_HOME:-$HOME/.local/share}/arcanum-native-port"
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/arcanum-native-port"
BIN_DIR="$HOME/.local/bin"

GOG_EXE=""
ORIG_DIR=""
UAP_EXE=""
WIDESCREEN="on"
COOP="on"
FULLSCREEN="on"
COMPACT_UI="off"
MAKE_LAUNCHER=1
GAME_DIR=""
COVER_OVERWRITE=0

while [ $# -gt 0 ]; do
    case "$1" in
        --yes|--force) shift ;;
        --gog-installer) GOG_EXE="${2:-}"; shift 2 ;;
        --original|--data-dir) ORIG_DIR="${2:-}"; shift 2 ;;
        --uap) UAP_EXE="${2:-}"; shift 2 ;;
        --widescreen) WIDESCREEN="${2:-on}"; shift 2 ;;
        --coop) COOP="${2:-on}"; shift 2 ;;
        --fullscreen) FULLSCREEN="${2:-on}"; shift 2 ;;
        --compact-ui) COMPACT_UI="${2:-off}"; shift 2 ;;
        --no-launcher) MAKE_LAUNCHER=0; shift ;;
        --game-dir) GAME_DIR="${2:-}"; shift 2 ;;
        --cover-overwrite) COVER_OVERWRITE=1; shift ;;
        -h|--help)
            cat <<'EOF'
Usage: ./install [--gog-installer setup_arcanum_*.exe | --original /path/to/Arcanum]
                 [--uap ArcanumUnofficialPatchV2.0.2.exe]
                 [--widescreen on|off] [--coop on|off] [--fullscreen on|off]
                 [--compact-ui on|off] [--no-launcher]
                 [--game-dir /path/to/console/game/folder] [--cover-overwrite]
  --game-dir         Console game folder (holding launch.sh, e.g. VIM1S
                     /mnt/games/games/Arcanum) that receives cover.png.
  --cover-overwrite  Replace an existing, different cover.png there (default: keep).
EOF
            exit 0 ;;
        *) printf "Warning: ignoring unknown option %s\n" "$1"; shift ;;
    esac
done

if [ -z "$GOG_EXE" ] && [ -z "$ORIG_DIR" ]; then
    printf "ERROR: Specify --gog-installer <setup_arcanum_*.exe> or --original <game_folder>.\n" >&2
    exit 1
fi

mkdir -p "$INSTALL_ROOT/bin" "$CONFIG_DIR" "$BIN_DIR"

# 1. Install native 64-bit arcport engine binaries & clean-room documentation
printf "Installing native 64-bit arcport v%s binaries...\n" "$ARC_VERSION"
cp -f "$PKG_DIR/bin/"* "$INSTALL_ROOT/bin/"
chmod +x "$INSTALL_ROOT/bin/"*
for doc in README.md LICENSE LICENSE-docs LEGAL.md THIRD_PARTY.md VERSION; do
    [ -f "$PKG_DIR/$doc" ] && cp -f "$PKG_DIR/$doc" "$INSTALL_ROOT/"
done

# 2. Extract or verify user's own Arcanum data (clean data only, no Win32 binaries)
DATA_TARGET="$INSTALL_ROOT/gamedata"
find_arc_root() {
    _found=$(find "$1" -maxdepth 4 \( -iname 'arcanum1.dat' -o -iname 'arcanum.dat' \) 2>/dev/null | head -n 1 || true)
    if [ -n "$_found" ]; then
        dirname "$_found"
    fi
}

STAGE_EXTRACT=""
cleanup_stage() {
    [ -n "$STAGE_EXTRACT" ] && rm -rf -- "$STAGE_EXTRACT"
}
trap cleanup_stage EXIT INT TERM

if [ -n "$GOG_EXE" ]; then
    if [ ! -f "$GOG_EXE" ]; then
        printf "ERROR: GOG installer not found: %s\n" "$GOG_EXE" >&2
        exit 1
    fi
    if ! command -v innoextract >/dev/null 2>&1; then
        printf "ERROR: 'innoextract' is required to unpack GOG .exe installers.\n" >&2
        printf "Install it via your package manager (e.g. sudo apt install innoextract) and retry.\n" >&2
        exit 1
    fi
    printf "Extracting GOG installer via innoextract (this takes ~10-30s)...\n"
    STAGE_EXTRACT=$(mktemp -d "${TMPDIR:-/tmp}/arcport-extract.XXXXXX")
    innoextract -s -d "$STAGE_EXTRACT" "$GOG_EXE"

    SRC_DATA_DIR=$(find_arc_root "$STAGE_EXTRACT")
    if [ -z "$SRC_DATA_DIR" ]; then
        printf "ERROR: Arcanum1.dat not found inside %s. Verify it is the Arcanum GOG installer.\n" "$GOG_EXE" >&2
        exit 1
    fi
    rm -rf "$DATA_TARGET"
    mkdir -p "$DATA_TARGET"
    cp -Rf "$SRC_DATA_DIR/." "$DATA_TARGET/"
    find "$DATA_TARGET" \( -iname '*.exe' -o -iname '*.dll' -o -iname '*.bat' \) -delete 2>/dev/null || true
    FINAL_DATA_DIR="$DATA_TARGET"
else
    if [ ! -d "$ORIG_DIR" ]; then
        printf "ERROR: Game directory not found: %s\n" "$ORIG_DIR" >&2
        exit 1
    fi
    SRC_DATA_DIR=$(find_arc_root "$ORIG_DIR")
    if [ -z "$SRC_DATA_DIR" ]; then
        printf "ERROR: Arcanum1.dat / Arcanum.dat not found inside %s.\n" "$ORIG_DIR" >&2
        exit 1
    fi
    SRC_DATA_DIR=$(CDPATH='' cd -- "$SRC_DATA_DIR" && pwd -P)
    if [ -n "$UAP_EXE" ]; then
        printf "Copying verified Arcanum data to %s before applying UAP...\n" "$DATA_TARGET"
        rm -rf "$DATA_TARGET"
        mkdir -p "$DATA_TARGET"
        cp -Rf "$SRC_DATA_DIR/." "$DATA_TARGET/"
        find "$DATA_TARGET" \( -iname '*.exe' -o -iname '*.dll' -o -iname '*.bat' \) -delete 2>/dev/null || true
        FINAL_DATA_DIR="$DATA_TARGET"
    else
        FINAL_DATA_DIR="$SRC_DATA_DIR"
    fi
fi

# 2a. Optional Unofficial Arcanum Patch (UAP) data overlay
if [ -n "$UAP_EXE" ]; then
    if [ ! -f "$UAP_EXE" ]; then
        printf "ERROR: UAP installer not found: %s\n" "$UAP_EXE" >&2
        exit 1
    fi
    if ! command -v innoextract >/dev/null 2>&1; then
        printf "WARNING: 'innoextract' not installed; skipping UAP extraction.\n" >&2
    else
        printf "Extracting UAP data overlay via innoextract...\n"
        UAP_STAGE=$(mktemp -d "${TMPDIR:-/tmp}/arcport-uap.XXXXXX")
        innoextract -s -d "$UAP_STAGE" "$UAP_EXE" || true
        UAP_APP="$UAP_STAGE/app"
        [ -d "$UAP_APP" ] || UAP_APP="$UAP_STAGE"
        find "$UAP_APP" \( -iname '*.exe' -o -iname '*.dll' -o -iname '*.bat' \) -delete 2>/dev/null || true
        cp -Rf "$UAP_APP/." "$FINAL_DATA_DIR/" 2>/dev/null || true
        rm -rf -- "$UAP_STAGE"
        printf "Applied UAP data overlay into %s.\n" "$FINAL_DATA_DIR"
    fi
fi

rm -rf -- "$STAGE_EXTRACT" 2>/dev/null || true
STAGE_EXTRACT=""
trap - EXIT INT TERM

printf "Verified game data in %s\n" "$FINAL_DATA_DIR"

# 2b. VIM1S console cover (original 309x156 PNG) — copied verbatim, never re-encoded.
COVER_SRC="$PKG_DIR/cover.png"
if [ -f "$COVER_SRC" ]; then
    cp -f "$COVER_SRC" "$INSTALL_ROOT/cover.png"
    if [ -z "$GAME_DIR" ]; then
        for _d in "$FINAL_DATA_DIR" "$ORIG_DIR"; do
            if [ -n "$_d" ] && [ -f "$_d/launch.sh" ]; then GAME_DIR="$_d"; break; fi
        done
    fi
    if [ -n "$GAME_DIR" ]; then
        if [ ! -f "$GAME_DIR/launch.sh" ]; then
            printf "Warning: no launch.sh in %s; not placing cover.png there.\n" "$GAME_DIR" >&2
        elif [ -f "$GAME_DIR/cover.png" ] && ! cmp -s "$COVER_SRC" "$GAME_DIR/cover.png" && [ "$COVER_OVERWRITE" -ne 1 ]; then
            printf "Kept existing %s/cover.png (use --cover-overwrite to replace it).\n" "$GAME_DIR"
        else
            cp -f "$COVER_SRC" "$GAME_DIR/cover.png.new" && mv -f "$GAME_DIR/cover.png.new" "$GAME_DIR/cover.png"
            printf "Installed console cover: %s/cover.png\n" "$GAME_DIR"
        fi
    fi
fi

# 3. Write configuration & launcher wrapper
WS_VAL=1; [ "$WIDESCREEN" = "off" ] && WS_VAL=0
COOP_VAL=1; [ "$COOP" = "off" ] && COOP_VAL=0
FS_VAL=1; [ "$FULLSCREEN" = "off" ] && FS_VAL=0
CU_VAL=0; [ "$COMPACT_UI" = "on" ] && CU_VAL=1

FS_FLAG=""; [ "$FS_VAL" -eq 1 ] && FS_FLAG="--fullscreen"
CU_FLAG=""; [ "$CU_VAL" -eq 1 ] && CU_FLAG="--compact-ui"
COOP_FLAG=""; [ "$COOP_VAL" -eq 1 ] && COOP_FLAG="--coop"

cat > "$CONFIG_DIR/settings.cfg" <<EOF
# Arcanum: Of Steamworks and Magick Obscura — arcport v$ARC_VERSION settings
widescreen=$WS_VAL
coop=$COOP_VAL
fullscreen=$FS_VAL
compact_ui=$CU_VAL
data_dir=$FINAL_DATA_DIR
EOF

# shellcheck disable=SC2086
cat > "$BIN_DIR/arcanum-native-port" <<EOF
#!/bin/sh
set -eu
DATA_DIR="$FINAL_DATA_DIR"
if [ \$# -gt 0 ]; then
    exec "$INSTALL_ROOT/bin/arcport" --data "\$DATA_DIR" "\$@"
fi
exec "$INSTALL_ROOT/bin/arcport" --window --data "\$DATA_DIR" --widescreen="$WS_VAL" $COOP_FLAG $FS_FLAG $CU_FLAG
EOF
chmod +x "$BIN_DIR/arcanum-native-port"
printf "Created launcher: %s/arcanum-native-port\n" "$BIN_DIR"

# 4. Create Desktop & Application Menu shortcuts
if [ "$MAKE_LAUNCHER" -eq 1 ]; then
    APP_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
    mkdir -p "$APP_DIR"
    DESKTOP_FILE="$APP_DIR/arcanum-native-port.desktop"
    cat > "$DESKTOP_FILE" <<EOF
[Desktop Entry]
Type=Application
Version=1.0
Name=Arcanum: Of Steamworks and Magick Obscura
GenericName=Steampunk Fantasy CRPG (Native 64-Bit Port)
Comment=Play Arcanum natively via arcport v$ARC_VERSION (16:10 + 1-2P Couch Co-op)
Exec=$BIN_DIR/arcanum-native-port
Terminal=false
Categories=Game;RolePlaying;
StartupNotify=true
EOF
    chmod +x "$DESKTOP_FILE"
    if [ -d "$HOME/Desktop" ]; then
        cp -f "$DESKTOP_FILE" "$HOME/Desktop/arcanum-native-port.desktop"
        chmod +x "$HOME/Desktop/arcanum-native-port.desktop"
        if command -v gio >/dev/null 2>&1; then
            gio set "$HOME/Desktop/arcanum-native-port.desktop" metadata::trusted true 2>/dev/null || true
        fi
    fi
    printf "Created Desktop & Application Menu shortcuts.\n"
fi

printf "Arcanum: Of Steamworks and Magick Obscura (arcport v%s) installed cleanly!\n" "$ARC_VERSION"
