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

PLUGIN_NAME="NextATC"
PLUGIN_FOLDER="$PLUGIN_NAME"

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

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SRC="$SCRIPT_DIR/$PLUGIN_FOLDER"

PRESERVE="settings.ini voices.ini FlightPlan.txt Settings.txt Voices.txt"

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_conflicting() {
    local pluginsDir="$1/Resources/plugins"
    for d in "$pluginsDir"/124th*; do [ -d "$d" ] && echo "$d"; done
    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 Linux (2026)      ${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} $SRC"
    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/lin_x64/$PLUGIN_FOLDER.xpl" ] && HAS_BIN=1
[ -f "$SRC/mac_x64/$PLUGIN_FOLDER.xpl" ] && HAS_BIN=1
[ -f "$SRC/win_x64/$PLUGIN_FOLDER.xpl" ] && HAS_BIN=1
if [ $HAS_BIN -eq 0 ]; then
    echo -e "  ${R}Error: No plugin binaries found in: $SRC${Z}"; 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 — recommended (Steam + common locations)"
    echo -e "    [${W}D${Z}] Deep search — full filesystem scan (slower)"
    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
        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 -e "  ${Y}Deep search in progress (may take 30-90 seconds)...${Z}"
        while IFS= read -r i; do [ -n "$i" ] && INSTALLS+=("$i"); done < <(find /home /mnt /media /opt /srv /run/media -type d -name "Global Scenery" -maxdepth 8 2>/dev/null)
    else
        echo -e "  ${W}Quick search in progress...${Z}"
        # Steam + percorsi comuni
        STEAM_PATHS=("$HOME/.steam/steam/steamapps/common" "$HOME/.local/share/Steam/steamapps/common" "/opt")
        for base in "${STEAM_PATHS[@]}"; do
            for name in "X-Plane 12" "X-Plane12" "XPlane 12" "XPlane12" "X-Plane 11" "X-Plane11"; do
                d="$base/$name"
                [ -d "$d" ] && is_xplane "$d" && INSTALLS+=("$d")
            done
        done
        # Root dei mount points esterni
        for v in /mnt/* /media/* /run/media/*/; do
            [ -d "$v" ] || continue
            for name in "X-Plane 12" "X-Plane12" "XPlane 12" "XPlane12" "X-Plane 11" "X-Plane11"; do
                d="$v$name"
                [ -d "$d" ] && is_xplane "$d" && INSTALLS+=("$d")
            done
        done
    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[@]} installations:${Z}"
    for i in "${!INSTALLS[@]}"; do echo -e "    [${W}$((i+1))${Z}] ${INSTALLS[$i]}"; done
    echo -e "    [${W}A${Z}] All  [${W}Q${Z}] Quit"
    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}"; exit 1
    fi
fi

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

    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

    DEST="$XP/Resources/plugins/$PLUGIN_FOLDER"
    MODE="fresh"

    if [ -d "$DEST" ]; then
        MODE="update"
        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
            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

    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; }

    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

    mkdir -p "$DEST" || { echo -e "  ${R}Error: could not create plugin folder${Z}"; continue; }

    # Migrate navdata
    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
                        mv "$cdir/navdata" "$DEST/navdata" && echo -e "  ${W}Navdata migrated.${Z}"
                    fi
                    break
                fi
            fi
        done
    fi

    # Clean old binaries
    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 files
    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")"
        for pf in $PRESERVE; do
            [ "$rel" = "$pf" ] && [ -f "$destFile" ] && continue 2
        done
        case "$rel" in navdata/*) [ -d "$DEST/navdata" ] && continue ;; esac
        mkdir -p "$destDir"
        cp -f "$sf" "$destFile" || COPY_ERRORS=$((COPY_ERRORS+1))
    done < <(find "$SRC" -type f)
    [ $COPY_ERRORS -gt 0 ] && echo -e "  ${R}Warning: $COPY_ERRORS file(s) failed to copy.${Z}"

    # Archive conflicting plugins
    if [ ${#CONFLICTING_DIRS[@]} -gt 0 ]; then
        BACKUP_DIR="$DEST/backup"
        mkdir -p "$BACKUP_DIR"
        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 — conflicting plugins left in place.${Z}"
        fi
    fi

    # Dependency check
    XPL="$DEST/lin_x64/$PLUGIN_FOLDER.xpl"
    if [ -f "$XPL" ] && command -v ldd >/dev/null 2>&1; then
        echo ""
        echo -e "  ${W}Checking dependencies...${Z}"
        MISSING=""
        while IFS= read -r line; do
            if echo "$line" | grep -q "not found"; then
                MISSING="$MISSING $(echo "$line" | awk '{print $1}')"
            fi
        done < <(ldd "$XPL" 2>/dev/null)
        if [ -n "$MISSING" ]; then
            echo -e "  ${R}Missing libraries:${Z}$MISSING"
            # ... (il blocco di suggerimenti pacchetti è identico al tuo originale)
        else
            echo -e "  ${W}All dependencies OK.${Z}"
        fi
    fi

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

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

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

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