#!/bin/sh
# ============================================================================
# Warlords III: Darklords Rising — Native 64-Bit Port (realmrun v1.0.0)
# Installer Backend (invoked by Graphical Setup Wizard or CLI --cli)
# ============================================================================
set -eu

PKG_DIR=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P)
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"
COOP="on"
FULLSCREEN="on"
MAKE_LAUNCHER=1

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 ;;
        --coop) COOP="${2:-on}"; shift 2 ;;
        --fullscreen) FULLSCREEN="${2:-on}"; shift 2 ;;
        --no-launcher) MAKE_LAUNCHER=0; shift ;;
        -h|--help)
            cat <<'EOF'
Usage: ./install [--gog-installer setup_warlords_iii_*.exe | --original /path/to/Warlords3]
                 [--w3cp on|off] [--coop on|off] [--fullscreen on|off] [--no-launcher]
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 v1.0.0 binaries...\n"
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; 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"

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

# 3. Write configuration & settings
W3CP_VAL=1; [ "$W3CP" = "off" ] && W3CP_VAL=0
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 v1.0.0 settings
# Includes Warlords III Code Patch (W3CP) fixes by trixy (https://www.moddb.com/mods/warlords-iii-code-patch)
codepatch_fixes=$W3CP_VAL
fullscreen=$( [ "$FULLSCREEN" = "on" ] && echo 1 || echo 0 )
data_dir=$FINAL_DATA_DIR
rules_file=$RUL_BASENAME
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"
export REALMRUN_CODEPATCH_FIXES="$W3CP_VAL"
if [ \$# -gt 0 ]; then
    exec "$INSTALL_ROOT/bin/realmrun" "\$@"
fi
exec "$INSTALL_ROOT/bin/realmrun" $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 v1.0.0 (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 v1.0.0) installed cleanly!\n"
