#!/bin/bash
# ============================================================================
# Plugin Installer for MacOS
# ============================================================================

# Plugin identity
PLUGIN_NAME="NextATC"
PLUGIN_FOLDER="$PLUGIN_NAME"

# Colors
R="\033[38;5;197m"; Y="\033[38;5;183m"
P="\033[1;35m"; W="\033[0m"; Z="\033[0m"

# Source directory = plugin subfolder next to this script
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SRC="$SCRIPT_DIR/$PLUGIN_FOLDER"

# Files to never overwrite (user data)
PRESERVE="settings.ini voices.ini FlightPlan.txt Settings.txt Voices.txt"

# ── Helpers ──────────────────────────────────────────────────────────────────

is_xplane() {
    [ -d "$1/Resources/plugins" ] || return 1
    local s=0
    [ -d "$1/Aircraft" ]       && s=$((s+1))
    [ -d "$1/Airfoils" ]       && s=$((s+1))
    [ -d "$1/Global Scenery" ] && s=$((s+1))
    [ $s -ge 2 ]
}

find_installs_quick() {
    local names=(
        "X-Plane 12" "X-Plane 11" "X-Plane 10"
        "XPlane12"   "XPlane11"   "XPlane10"
        "X-Plane"    "XPlane"
    )
    local bases=("$HOME" "/Applications")
    for v in /Volumes/*/; do [ -d "$v" ] && bases+=("${v%/}"); done

    for base in "${bases[@]}"; do
        for name in "${names[@]}"; do
            local d="$base/$name"
            [ -d "$d" ] && is_xplane "$d" && echo "$d"
        done
    done
}

find_installs_deep() {
    # Search for "Global Scenery" folder (unique to X-Plane); parent = X-Plane root.
    # Confirm X-Plane.app is present before validating with is_xplane.
    while IFS= read -r gs; do
        local p
        p="$(dirname "$gs")"
        [ -d "$p/X-Plane.app" ] || continue
        is_xplane "$p" && echo "$p"
    done < <(find /Users /Applications /Volumes -type d -name "Global Scenery" 2>/dev/null)
}

find_conflicting() {
    # Find all folders named 124th* and folders containing 124th*.xpl
    local pluginsDir="$1/Resources/plugins"
    # Folders named 124th*
    for d in "$pluginsDir"/124th*; do
        [ -d "$d" ] && echo "$d"
    done
    # Folders containing 124th*.xpl (in case folder has a different name)
    while IFS= read -r xpl; do
        local d
        d=$(dirname "$(dirname "$xpl")")
        [ "$(basename "$d")" = "$PLUGIN_FOLDER" ] && continue
        echo "$d"
    done < <(find "$pluginsDir" -maxdepth 3 -name "124th*.xpl" 2>/dev/null)
}

# ── Banner ───────────────────────────────────────────────────────────────────

clear
echo ""
echo -e "  ${P}======================================================${Z}"
echo -e "  ${P}          $PLUGIN_NAME — Installer for macOS              ${Z}"
[ -f "$SRC/Version.txt" ] && echo -e "  ${W}          Version: $(cat "$SRC/Version.txt")${Z}"
echo -e "  ${P}======================================================${Z}"
echo ""

# ── Verify source ────────────────────────────────────────────────────────────

if [ ! -d "$SRC" ]; then
    echo -e "  ${R}Error: Plugin folder not found at:${Z}"
    echo -e "  $SRC"
    echo ""
    echo -e "  Make sure the ${W}$PLUGIN_FOLDER${Z} folder is next to this script."
    echo ""
    read -p "  Press Enter to close..." _
    exit 1
fi

HAS_BIN=0
[ -f "$SRC/mac_x64/$PLUGIN_FOLDER.xpl" ] && HAS_BIN=1
[ -f "$SRC/win_x64/$PLUGIN_FOLDER.xpl" ] && HAS_BIN=1
[ -f "$SRC/lin_x64/$PLUGIN_FOLDER.xpl" ] && HAS_BIN=1

if [ $HAS_BIN -eq 0 ]; then
    echo -e "  ${R}Error: No plugin binaries found in:${Z}"
    echo -e "  $SRC"
    echo ""
    read -p "  Press Enter to close..." _
    exit 1
fi

# ── Find X-Plane ─────────────────────────────────────────────────────────────

INSTALLS=()
while [ ${#INSTALLS[@]} -eq 0 ]; do
    echo -e "  ${W}How would you like to find your X-Plane installation?${Z}"
    echo ""
    echo -e "    [${W}S${Z}] Quick search — common locations (recommended)"
    echo -e "    [${W}D${Z}] Deep search — scan entire filesystem (slow)"
    echo -e "    [${W}M${Z}] Enter path manually"
    echo -e "    [${W}Q${Z}] Quit"
    echo ""
    read -p "  Select [S/d/m/q]: " choice
    choice="${choice:-S}"

    if [[ "$choice" =~ ^[Qq]$ ]]; then
        exit 0
    elif [[ "$choice" =~ ^[Mm]$ ]]; then
        echo ""
        read -p "  Enter X-Plane folder path: " mp
        mp="${mp/#\~/$HOME}"
        if is_xplane "$mp"; then
            INSTALLS+=("$mp")
        else
            echo -e "  ${R}Not a valid X-Plane folder.${Z}"
            echo ""
        fi
    elif [[ "$choice" =~ ^[Dd]$ ]]; then
        echo ""
        echo -e "  ${Y}Scanning filesystem for X-Plane installations...${Z}"
        while IFS= read -r i; do [ -n "$i" ] && INSTALLS+=("$i"); done < <(find_installs_deep)
        [ ${#INSTALLS[@]} -eq 0 ] && echo -e "  ${R}X-Plane not found. Use [M] to enter the path manually.${Z}" && echo ""
    else
        echo ""
        echo -e "  ${W}Searching common locations...${Z}"
        while IFS= read -r i; do [ -n "$i" ] && INSTALLS+=("$i"); done < <(find_installs_quick)
        [ ${#INSTALLS[@]} -eq 0 ] && echo -e "  ${Y}Not found. Try [D] for a full filesystem scan.${Z}" && echo ""
    fi
done

# ── Select installation ──────────────────────────────────────────────────────

echo ""
if [ ${#INSTALLS[@]} -eq 1 ]; then
    echo -e "  ${W}Found:${Z} ${INSTALLS[0]}"
elif [ ${#INSTALLS[@]} -gt 1 ]; then
    echo -e "  ${W}Found ${#INSTALLS[@]} X-Plane installations:${Z}"
    echo ""
    for i in "${!INSTALLS[@]}"; do
        echo -e "    [${W}$((i+1))${Z}] ${INSTALLS[$i]}"
    done
    echo -e "    [${W}A${Z}] Install to ALL"
    echo -e "    [${W}Q${Z}] Quit"
    echo ""
    read -p "  Select: " sel
    [[ "$sel" =~ ^[Qq]$ ]] && exit 0
    if [[ "$sel" =~ ^[0-9]+$ ]] && [ "$sel" -ge 1 ] && [ "$sel" -le ${#INSTALLS[@]} ]; then
        INSTALLS=("${INSTALLS[$((sel-1))]}")
    elif [[ ! "$sel" =~ ^[Aa]$ ]]; then
        echo -e "  ${R}Invalid.${Z}"; read -p "  Press Enter..." _; exit 1
    fi
fi

# ── Process each installation ────────────────────────────────────────────────

for XP in "${INSTALLS[@]}"; do
    echo ""
    echo -e "  ${P}──────────────────────────────────────────────────${Z}"
    echo -e "  ${P}Processing: ${W}$XP${Z}"
    echo -e "  ${P}──────────────────────────────────────────────────${Z}"

    # Scan for conflicting plugins (folders named 124th* or containing 124th*.xpl)
    CONFLICTING_DIRS=()
    while IFS= read -r cdir; do
        [ -n "$cdir" ] && CONFLICTING_DIRS+=("$cdir")
    done < <(find_conflicting "$XP" | sort -u)

    for d in "${CONFLICTING_DIRS[@]}"; do
        echo -e "  ${Y}Conflicting plugin found — will be backed up: $d${Z}"
    done

    # Detect existing installation (our own folder only)
    DEST="$XP/Resources/plugins/$PLUGIN_FOLDER"
    MODE="fresh"

    if [ -d "$DEST" ]; then
        MODE="update"
        echo ""
        echo -e "  ${Y}Existing installation found:${Z} $DEST"
        INSTALLED_VER=""
        [ -f "$DEST/Version.txt" ] && INSTALLED_VER=$(cat "$DEST/Version.txt") && echo -e "  ${W}Installed:${Z} $INSTALLED_VER"
        NEW_VER=""
        [ -f "$SRC/Version.txt" ] && NEW_VER=$(cat "$SRC/Version.txt") && echo -e "  ${W}New:      ${Z} $NEW_VER"
        if [ -n "$INSTALLED_VER" ] && [ -n "$NEW_VER" ] && [ "$INSTALLED_VER" = "$NEW_VER" ]; then
            # Integrity check: every file in source must exist in destination
            MISSING=""
            while IFS= read -r sf; do
                rel="${sf#$SRC/}"
                case "$rel" in .DS_Store|*/.DS_Store) continue ;; esac
                [ ! -f "$DEST/$rel" ] && MISSING="$MISSING $rel"
            done < <(find "$SRC" -type f)
            if [ -n "$MISSING" ]; then
                echo -e "  ${Y}Incomplete installation detected — missing files:${Z}"
                for mf in $MISSING; do echo -e "    ${R}$mf${Z}"; done
                echo -e "  ${W}Repairing...${Z}"
                MODE="repair"
            else
                echo -e "  ${W}Already up to date — skipping.${Z}"
                continue
            fi
        fi
    fi

    # ── Confirm ───────────────────────────────────────────────────
    echo ""
    echo -e "  ${W}Destination:${Z} $DEST"
    if [ "$MODE" = "repair" ]; then
        echo -e "  ${W}Action:${Z} ${Y}Repair in place${Z}"
        echo -e "  ${W}Your settings and navdata will be preserved.${Z}"
    elif [ "$MODE" = "update" ]; then
        echo -e "  ${W}Action:${Z} ${Y}Update in place${Z}"
        echo -e "  ${W}Your settings and navdata will be preserved.${Z}"
    else
        echo -e "  ${W}Action:${Z} ${W}New installation${Z}"
    fi
    echo ""
    read -p "  Proceed? [Y/n]: " go
    [[ -z "$go" || "$go" =~ ^[Yy]$ ]] || { echo "  Skipped."; continue; }

    # ── Install ──────────────────────────────────────────────────────────
    echo ""
    if [ "$MODE" = "repair" ]; then
        echo -e "  ${W}Repairing...${Z}"
    elif [ "$MODE" = "update" ]; then
        echo -e "  ${W}Updating...${Z}"
    else
        echo -e "  ${W}Installing...${Z}"
    fi
    if ! mkdir -p "$DEST"; then
        echo -e "  ${R}Error: could not create plugin folder: $DEST${Z}"
        echo -e "  ${R}Check permissions and try again.${Z}"
        continue
    fi

    # Migrate navdata from conflicting plugin if available
    if [ ${#CONFLICTING_DIRS[@]} -gt 0 ] && [ ! -d "$DEST/navdata" ]; then
        for cdir in "${CONFLICTING_DIRS[@]}"; do
            if [ -d "$cdir/navdata" ]; then
                NAV_COUNT=$(find "$cdir/navdata" -type f 2>/dev/null | wc -l | tr -d ' ')
                if [ "$NAV_COUNT" -gt 0 ]; then
                    echo ""
                    echo -e "  ${W}Navdata found in \"$(basename "$cdir")\" ($NAV_COUNT files).${Z}"
                    read -p "  Migrate navdata to $PLUGIN_NAME? [Y/n]: " migNav
                    if [[ -z "$migNav" || "$migNav" =~ ^[Yy]$ ]]; then
                        if mv "$cdir/navdata" "$DEST/navdata"; then
                            echo -e "  ${W}Navdata migrated.${Z}"
                        else
                            echo -e "  ${R}Error: could not migrate navdata — check permissions.${Z}"
                        fi
                    fi
                    break
                fi
            fi
        done
    fi

    # Clean old binaries silently (upgrade/repair: remove stale libs before copying new)
    if [ "$MODE" = "update" ] || [ "$MODE" = "repair" ]; then
        for pd in mac_x64 win_x64 lin_x64 64; do
            rm -f "$DEST/$pd"/*.xpl "$DEST/$pd"/*.dll 2>/dev/null
        done
    fi

    # Copy all files from source package
    COPY_ERRORS=0
    while IFS= read -r sf; do
        rel="${sf#$SRC/}"
        case "$rel" in .DS_Store|*/.DS_Store) continue ;; esac
        destFile="$DEST/$rel"
        destDir="$(dirname "$destFile")"
        # Preserved files: copy only if missing (user data)
        for pf in $PRESERVE; do
            [ "$rel" = "$pf" ] && [ -f "$destFile" ] && continue 2
        done
        # Navdata: copy only if navdata dir doesn't exist yet
        case "$rel" in navdata/*) [ -d "$DEST/navdata" ] && continue ;; esac
        if [ ! -d "$destDir" ]; then
            if ! mkdir -p "$destDir"; then
                echo -e "  ${R}Error: could not create directory: $destDir${Z}"
                COPY_ERRORS=$((COPY_ERRORS+1))
                continue
            fi
        fi
        if ! cp -f "$sf" "$destFile"; then
            echo -e "  ${R}Error: could not copy: $rel${Z}"
            COPY_ERRORS=$((COPY_ERRORS+1))
        fi
    done < <(find "$SRC" -type f)
    if [ $COPY_ERRORS -gt 0 ]; then
        echo -e "  ${R}Warning: $COPY_ERRORS file(s) failed to copy — installation may be incomplete.${Z}"
        echo -e "  ${R}Check disk space and permissions, then try again.${Z}"
    fi

    # Archive conflicting plugin folders into $DEST/backup/legacy.zip (or .tar.gz)
    if [ ${#CONFLICTING_DIRS[@]} -gt 0 ]; then
        BACKUP_DIR="$DEST/backup"
        if ! mkdir -p "$BACKUP_DIR"; then
            echo -e "  ${R}Error: could not create backup folder: $BACKUP_DIR${Z}"
            echo -e "  ${R}Conflicting plugins were NOT backed up — remove them manually if needed.${Z}"
        else
            PLUGINS_DIR="$XP/Resources/plugins"
            BNAMES=()
            for cdir in "${CONFLICTING_DIRS[@]}"; do BNAMES+=("$(basename "$cdir")"); done

            ARCHIVE_OK=0
            if command -v zip >/dev/null 2>&1; then
                ARCHIVE="$BACKUP_DIR/legacy.zip"
                (cd "$PLUGINS_DIR" && zip -r "$ARCHIVE" "${BNAMES[@]}" 2>/dev/null) && ARCHIVE_OK=1
            fi
            if [ $ARCHIVE_OK -eq 0 ] && command -v tar >/dev/null 2>&1; then
                ARCHIVE="$BACKUP_DIR/legacy.tar.gz"
                tar -czf "$ARCHIVE" -C "$PLUGINS_DIR" "${BNAMES[@]}" 2>/dev/null && ARCHIVE_OK=1
            fi

            if [ $ARCHIVE_OK -eq 1 ]; then
                echo -e "  ${W}Conflicting plugins archived → $PLUGIN_NAME/backup/$(basename "$ARCHIVE")${Z}"
                for cdir in "${CONFLICTING_DIRS[@]}"; do rm -rf "$cdir"; done
            else
                echo -e "  ${R}No archive tool found (zip/tar) — conflicting plugins left in place.${Z}"
                echo -e "  ${R}Remove manually to avoid conflicts: ${CONFLICTING_DIRS[*]}${Z}"
            fi
        fi
    fi

    # macOS: remove quarantine
    xattr -dr com.apple.quarantine "$DEST" 2>/dev/null
    if xattr "$DEST/mac_x64/$PLUGIN_FOLDER.xpl" 2>/dev/null | grep -q "quarantine"; then
        echo -e "  ${Y}Warning: could not fully remove quarantine.${Z}"
        echo -e "  Try: ${W}sudo xattr -dr com.apple.quarantine \"$DEST\"${Z}"
    fi

    # Done
    echo ""
    echo -e "  ${P}======================================================${Z}"
    if [ "$MODE" = "repair" ]; then
        echo -e "  ${W}Repair complete!${Z}"
        [ -f "$DEST/Version.txt" ] && echo -e "  ${W}Version:${Z}  $(cat "$DEST/Version.txt")"
    elif [ "$MODE" = "update" ] && [ -n "$INSTALLED_VER" ]; then
        FINAL_VER=""
        [ -f "$DEST/Version.txt" ] && FINAL_VER=$(cat "$DEST/Version.txt")
        echo -e "  ${W}Update complete!${Z}  $INSTALLED_VER → $FINAL_VER"
    else
        echo -e "  ${W}Installation complete!${Z}"
        [ -f "$DEST/Version.txt" ] && echo -e "  ${W}Version:${Z}  $(cat "$DEST/Version.txt")"
    fi
    echo -e "  ${W}Location:${Z} $DEST"
    echo -e "  ${P}======================================================${Z}"
done

echo ""
echo -e "  ${P}Enjoy $PLUGIN_NAME!${Z}"
echo ""

# Show changelog if available
CL_PATH=""
[ -f "$SRC/CHANGELOG.md" ] && CL_PATH="$SRC/CHANGELOG.md"
if [ -n "$CL_PATH" ]; then
    read -p "  Press Enter to view changelog..." _
    echo ""
    echo -e "  ${P}=== What's New ===${Z}"
    echo ""
    sed 's/^/  /' "$CL_PATH" | head -60
    echo ""
fi

read -p "  Press Enter to close..." _
