#!/bin/sh
# ============================================================================
# SPDX-License-Identifier: GPL-3.0-or-later
# Warlords III: Darklords Rising — Native 64-Bit Port (realmrun)
# Installer Backend (invoked by Graphical Setup Wizard or CLI --cli)
# Packaged by tools/make-release.sh; the version comes from the package VERSION file.
# ============================================================================
set -eu

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

GOG_EXE=""
ORIG_DIR=""
W3CP="on"
W3CP_TWEAKS="off"
COOP="on"
FULLSCREEN="on"
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 ;;
        --w3cp) W3CP="${2:-on}"; shift 2 ;;
        --w3cp-tweaks) W3CP_TWEAKS="${2:-off}"; shift 2 ;;
        --coop) COOP="${2:-on}"; shift 2 ;;
        --fullscreen) FULLSCREEN="${2:-on}"; 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_warlords_iii_*.exe | --original /path/to/Warlords3]
                 [--w3cp on|off] [--w3cp-tweaks on|off] [--coop on|off] [--fullscreen on|off] [--no-launcher]
                 [--game-dir /path/to/console/game/folder] [--cover-overwrite]
  --game-dir         Console game folder (the one holding launch.sh, e.g. the VIM1S
                     /mnt/games/games/Warlords3-Frontier) that receives cover.png.
                     Default: the game data folder, if it holds a launch.sh.
  --cover-overwrite  Replace an existing, different cover.png there (default: keep it).
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_warlords_iii_*.exe> or --original <game_folder>.\n" >&2
    exit 1
fi

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

# 1. Install realmrun native engine binaries & clean-room documentation
printf "Installing native 64-bit realmrun v%s binaries...\n" "$RR_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-NOTICES.txt VERSION; do
    [ -f "$PKG_DIR/$doc" ] && cp -f "$PKG_DIR/$doc" "$INSTALL_ROOT/"
done

# 2. Extract or link Warlords III: Darklords Rising game data (clean data only, no Win32 binaries)
DATA_TARGET="$INSTALL_ROOT/gamedata"
find_rul_file() {
    find "$1" -maxdepth 2 -iname 'frontier.rul' 2>/dev/null | head -n 1
}

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 click Install again.\n" >&2
        exit 1
    fi
    printf "Extracting GOG installer via innoextract (this takes ~10-20s)...\n"
    STAGE_EXTRACT=$(mktemp -d "${TMPDIR:-/tmp}/w3-extract.XXXXXX")
    cleanup_stage() { rm -rf "$STAGE_EXTRACT"; }
    trap cleanup_stage EXIT INT TERM
    innoextract -s -d "$STAGE_EXTRACT" "$GOG_EXE"

    RUL_FOUND=$(find_rul_file "$STAGE_EXTRACT")
    if [ -z "$RUL_FOUND" ]; then
        printf "ERROR: Frontier.rul not found inside %s. Verify it is the Warlords III: Darklords Rising installer.\n" "$GOG_EXE" >&2
        exit 1
    fi
    SRC_DATA_DIR=$(dirname "$RUL_FOUND")
    rm -rf "$DATA_TARGET"
    mkdir -p "$DATA_TARGET"
    cp -Rf "$SRC_DATA_DIR/." "$DATA_TARGET/"
    # Strip Windows executables/DLLs per clean-room policy
    find "$DATA_TARGET" -maxdepth 2 \( -iname '*.exe' -o -iname '*.dll' -o -iname '*.bat' \) -delete 2>/dev/null || true
    trap - EXIT INT TERM
    rm -rf "$STAGE_EXTRACT"
    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
    RUL_FOUND=$(find_rul_file "$ORIG_DIR")
    if [ -z "$RUL_FOUND" ]; then
        printf "ERROR: Frontier.rul not found inside %s.\n" "$ORIG_DIR" >&2
        exit 1
    fi
    FINAL_DATA_DIR=$(CDPATH='' cd -- "$(dirname "$RUL_FOUND")" && pwd -P)
fi

RUL_BASENAME=$(basename "$(find "$FINAL_DATA_DIR" -maxdepth 1 -iname 'frontier.rul' | head -n 1)")
[ -n "$RUL_BASENAME" ] || RUL_BASENAME="Frontier.rul"

# Install PixelLab campaign portraits for The Elves Return & The Huge Wars if present
CAMP_DIR=$(find "$FINAL_DATA_DIR" -maxdepth 1 -type d -iname 'campaign' 2>/dev/null | head -n 1 || true)
if [ -n "$CAMP_DIR" ] && [ -d "$PKG_DIR/share/campaign_art" ]; then
    ELVES_DIR=$(find "$CAMP_DIR" -maxdepth 1 -type d -iname 'elves' 2>/dev/null | head -n 1 || true)
    GIANTS_DIR=$(find "$CAMP_DIR" -maxdepth 1 -type d -iname 'giants' 2>/dev/null | head -n 1 || true)
    if [ -n "$ELVES_DIR" ] && [ -f "$PKG_DIR/share/campaign_art/Elves_Campaign.pcx" ]; then
        cp -f "$PKG_DIR/share/campaign_art/Elves_Campaign.pcx" "$ELVES_DIR/Campaign.pcx" 2>/dev/null || true
    fi
    if [ -n "$GIANTS_DIR" ] && [ -f "$PKG_DIR/share/campaign_art/Giants_Campaign.pcx" ]; then
        cp -f "$PKG_DIR/share/campaign_art/Giants_Campaign.pcx" "$GIANTS_DIR/Campaign.pcx" 2>/dev/null || true
    fi
fi

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

# 2b. VIM1S console cover (original Pixellab art, 309x156 PNG) — copied verbatim, never re-encoded.
#     Always kept in the install root; also placed next to launch.sh in a console game folder so the
#     VIM1S Games menu shows it on the tile. An existing different cover.png there is kept unless
#     --cover-overwrite is given (it may be a user's own cover).
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 & settings
W3CP_VAL=1; [ "$W3CP" = "off" ] && W3CP_VAL=0
W3CP_TW_VAL=0; [ "$W3CP_TWEAKS" = "on" ] && W3CP_TW_VAL=1
W3CP_ONOFF="on"; [ "$W3CP" = "off" ] && W3CP_ONOFF="off"
W3CP_TW_ONOFF="off"; [ "$W3CP_TWEAKS" = "on" ] && W3CP_TW_ONOFF="on"
FS_FLAG=""; [ "$FULLSCREEN" = "on" ] && FS_FLAG="--fullscreen"
SETUP_FLAG="--setup"; [ "$COOP" = "off" ] && SETUP_FLAG="--setup"

cat > "$CONFIG_DIR/settings.cfg" <<EOF
# Warlords III: Darklords Rising — realmrun v$RR_VERSION settings
# Includes Warlords III Code Patch (W3CP) fixes by trixy (https://www.moddb.com/mods/warlords-iii-code-patch)
codepatch_fixes=$W3CP_VAL
codepatch_tweaks=$W3CP_TW_VAL
fullscreen=$( [ "$FULLSCREEN" = "on" ] && echo 1 || echo 0 )
data_dir=$FINAL_DATA_DIR
rules_file=$RUL_BASENAME
EOF

cat > "$CONFIG_DIR/preset.toml" <<EOF
# Warlords III: Darklords Rising — realmrun v$RR_VERSION Launch Preset
# Credit: Warlords III Code Patch (W3CP) by trixy (https://www.moddb.com/mods/warlords-iii-code-patch)
data              = "$FINAL_DATA_DIR"
rules             = "$RUL_BASENAME"
campaigns         = "all"
resolution        = [640, 480]
scaling           = "nearest"
pause_when_hidden = true
music             = on
input             = ["controller", "touch", "mouse", "keyboard"]
controller        = "claw-default"

# Master W3CP switch (on|off)
codepatch_fixes              = $W3CP_ONOFF

# Core W3CP Bug Fixes, QoL & AI Fixes (trixy's wl3-code-patch-no-tweaks.cfg — ON by default)
codepatch.diplomacy-bugs       = on
codepatch.diplomacy-mod        = on
codepatch.acid-lightning-bugs  = on
codepatch.spell-weighing-bug   = on
codepatch.ai-skills            = on
codepatch.print-conquered-city = on
codepatch.low-space-bug        = on
codepatch.version              = on

# Optional W3CP Extreme Balance Tweaks (OFF by default unless enabled in Setup Wizard)
codepatch.spells               = $W3CP_TW_ONOFF
codepatch.hp                   = $W3CP_TW_ONOFF
codepatch.neutrals             = $W3CP_TW_ONOFF
codepatch.city                 = $W3CP_TW_ONOFF
codepatch.upkeep               = $W3CP_TW_ONOFF
codepatch.quest-penalty        = $W3CP_TW_ONOFF
codepatch.quest-communism      = $W3CP_TW_ONOFF
codepatch.quests               = $W3CP_TW_ONOFF
codepatch.sites-income         = $W3CP_TW_ONOFF
codepatch.map-view             = $W3CP_TW_ONOFF
codepatch.production-time      = off
EOF

# 4. Create ~/.local/bin/warlords3-native-port launcher
cat > "$BIN_DIR/warlords3-native-port" <<EOF
#!/bin/sh
set -eu
DATA_DIR="$FINAL_DATA_DIR"
RULES_FILE="$RUL_BASENAME"
PRESET_FILE="$CONFIG_DIR/preset.toml"
export REALMRUN_CODEPATCH_FIXES="$W3CP_VAL"
export REALMRUN_CODEPATCH_TWEAKS="$W3CP_TW_VAL"
if [ \$# -gt 0 ]; then
    exec "$INSTALL_ROOT/bin/realmrun" "\$@"
fi
exec "$INSTALL_ROOT/bin/realmrun" --preset "\$PRESET_FILE" $SETUP_FLAG $FS_FLAG --data "\$DATA_DIR" --rules "\$RULES_FILE"
EOF
chmod +x "$BIN_DIR/warlords3-native-port"
printf "Created launcher: %s/warlords3-native-port\n" "$BIN_DIR"

# 5. 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/warlords3-native-port.desktop"
    cat > "$DESKTOP_FILE" <<EOF
[Desktop Entry]
Type=Application
Version=1.0
Name=Warlords III: Darklords Rising
GenericName=Turn-Based Fantasy Strategy (Native 64-Bit Port)
Comment=Play Warlords III: Darklords Rising natively via realmrun v$RR_VERSION (W3CP + 1-8P Co-op)
Exec=$BIN_DIR/warlords3-native-port
Terminal=false
Categories=Game;StrategyGame;
StartupNotify=true
EOF
    chmod +x "$DESKTOP_FILE"
    if [ -d "$HOME/Desktop" ]; then
        cp -f "$DESKTOP_FILE" "$HOME/Desktop/warlords3-native-port.desktop"
        chmod +x "$HOME/Desktop/warlords3-native-port.desktop"
        if command -v gio >/dev/null 2>&1; then
            gio set "$HOME/Desktop/warlords3-native-port.desktop" metadata::trusted true 2>/dev/null || true
        fi
    fi
    printf "Created Desktop & Application Menu shortcuts.\n"
fi

printf "Warlords III: Darklords Rising (realmrun v%s) installed cleanly!\n" "$RR_VERSION"
