#!/bin/bash

# Complete post-configure installation script
# Supported OS: Ubuntu, OpenSUSE (and Debian)
#
# Full install:
#   curl -sLS https://get.chavkov.com/index.sh | bash
#
# Single-script execution (downloads tarball, runs one script):
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script <SCRIPT_NAME>
#   Example: curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 02-pyenv.sh
#
# Preset flags (convenience shortcuts):
#   --github-ssh    Run first available GitHub SSH script (80–83)
#   --claude        Run 22-claude.sh (Claude settings + permissions)
#   --claude-proxy  Run claude-proxy.sh (Bosch LLM Farms / liteLLM proxy setup)
#   --aliases       Run 01-shell-aliases.sh (~/.aliases)
#   --byobu         Run 18-byobu.sh
#   --tmux          Run 19-tmux.sh
#
# Individual scripts (--script SCRIPT_NAME or run from extracted tarball):
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 01-shell-aliases.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 02-pyenv.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 05-fnm.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 05-fzf.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 07-arkade.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 10-git.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 11-neovim.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 15-brew.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 16-kind-rootless-podman.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 17-gh.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 18-byobu.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 19-tmux.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 20-bin-scripts.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 22-claude.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 80-github_vchavkov.sh
#   (same for 81-github_vchavkov82.sh, 82-github_chv1sf.sh, 83-github_ns9-io.sh)
#
# Or download tarball and run any script locally:
#   curl -sLS https://get.chavkov.com/scripts.tar.gz | tar -xzf -
#   bash scripts/02-pyenv.sh
#   bash scripts/10-git.sh
#   # etc.
#
# External standalone scripts (not in tarball; run from repo or curl):

#   GitHub SSH:     curl -sLS https://get.chavkov.com/github-ssh-reconfig.sh | bash

#   Claude (settings): curl -sLS https://get.chavkov.com/claude-reconfig.sh | bash

#   Claude proxy:   ANTHROPIC_API_KEY=your-key curl -sLS https://get.chavkov.com/claude-proxy.sh | bash
#                   (Bosch LLM Farms / liteLLM; auto-creates ~/.litellm/.env and updates .bashrc)
#                   (For LXC: INSTALL_HOME=/home/vchavkov ANTHROPIC_API_KEY=key curl ... )

# ssh suse-03 "export ANTHROPIC_API_KEY=821fffdba04d4170ab703fa14ecd782b && curl -sLS https://get.chavkov.com/claude-proxy.sh | bash"

#   Claude batch:   ./claude-batch.sh  (multi-host: reconfig + ~/.aliases_claude on LXC/SSH targets)

#   Claude Code:   curl -sLS https://get.chavkov.com/claude.sh | bash  (if using claude/ setup)

set -euo pipefail

# Install browser/media/runtime dependencies up front (Playwright/system libs).
if [ -r /etc/os-release ]; then
    . /etc/os-release
    case "${ID:-}" in
        ubuntu|debian)
            echo "📦 Installing Ubuntu/Debian Playwright dependencies..."
            sudo apt-get update -y || true
            sudo apt-get install -y --no-install-recommends \
                libicu-dev \
                libxml2 \
                libxslt1.1 \
                gstreamer1.0-plugins-good \
                gstreamer1.0-plugins-bad \
                gstreamer1.0-libav \
                libgstreamer-plugins-bad1.0-0 \
                libflite1 \
                libhyphen0 \
                libmanette-0.2-0 \
                libavif16 \
                libwoff1 \
                libgles2 \
                libenchant-2-2 \
                libwebpdemux2 \
                libwebpmux3 \
                libx264-163 \
                xvfb \
                fonts-noto-color-emoji \
                fonts-liberation \
                xfonts-base || true
            ;;
        opensuse-leap|opensuse-tumbleweed|opensuse|suse|sles)
            echo "📦 Installing OpenSUSE base + media/font dependencies..."
            opensuse_pkg_exists() {
                local pkg="${1:?}"
                zypper -n se --match-exact "$pkg" | awk 'NR>4 { found=1 } END { exit(!found) }'
            }

            opensuse_add_first_available() {
                local selected=""
                for candidate in "$@"; do
                    if opensuse_pkg_exists "$candidate"; then
                        selected="$candidate"
                        break
                    fi
                done

                if [ -n "$selected" ]; then
                    OPEN_SUSE_PKGS+=("$selected")
                else
                    echo "⚠️  No package candidate found for: $*"
                fi
            }

            OPEN_SUSE_PKGS=()
            opensuse_add_first_available mozilla-nspr
            opensuse_add_first_available mozilla-nss
            opensuse_add_first_available libatk-1_0-0
            opensuse_add_first_available libatspi0 libatspi0-0
            opensuse_add_first_available gtk2 libgtk-2_0-0
            opensuse_add_first_available gtk3 libgtk-3-0
            opensuse_add_first_available at-spi2-core
            opensuse_add_first_available libcups2 libcups2-2 cups-libs
            opensuse_add_first_available libdrm2
            opensuse_add_first_available libdbus-1-3 dbus-1
            opensuse_add_first_available libxkbcommon0 libxkbcommon0-0
            opensuse_add_first_available libX11-6 libx11-6
            opensuse_add_first_available libXcomposite1 libxcomposite1
            opensuse_add_first_available libXdamage1 libxdamage1
            opensuse_add_first_available libXext6 libxext6
            opensuse_add_first_available libXfixes3 libxfixes3
            opensuse_add_first_available libXrandr2 libxrandr2
            opensuse_add_first_available libxcb1 libxcb1-1
            opensuse_add_first_available libxshmfence1
            opensuse_add_first_available libxrender1
            opensuse_add_first_available libpango-1_0-0 pango-tools
            opensuse_add_first_available libgbm1
            opensuse_add_first_available alsa-lib libasound2
            opensuse_add_first_available libicu76 libicu78 libicu77 libicu75 icu
            opensuse_add_first_available libxml2 libxml2-16
            opensuse_add_first_available libxslt1
            opensuse_add_first_available gstreamer-plugins-good
            opensuse_add_first_available gstreamer-plugins-bad
            opensuse_add_first_available gstreamer-plugins-libav
            opensuse_add_first_available libgstcodecparsers-1_0-0
            opensuse_add_first_available libgstfft-1_0-0
            opensuse_add_first_available flite-devel
            opensuse_add_first_available libhyphen0
            opensuse_add_first_available libmanette-0_2-0
            opensuse_add_first_available libavif16
            opensuse_add_first_available libwoff2dec1 libwoff2dec1_0_2
            opensuse_add_first_available Mesa-libGLESv2-2 Mesa-libGLESv2 libGLESv2-2 libGLESv2-3 libGLESv2
            opensuse_add_first_available libenchant-2-2
            opensuse_add_first_available libwebpdemux2
            opensuse_add_first_available libwebpmux3
            opensuse_add_first_available libx264-163 libx264-164 libx264-165 libx264-166 libx264-167 x264
            opensuse_add_first_available chromium chromium-browser
            opensuse_add_first_available MozillaFirefox firefox
            opensuse_add_first_available xorg-x11-server
            opensuse_add_first_available xorg-x11-server-Xvfb
            opensuse_add_first_available xauth
            opensuse_add_first_available xorg-x11-xauth
            opensuse_add_first_available xhost
            opensuse_add_first_available xdpyinfo
            opensuse_add_first_available xrandr
            opensuse_add_first_available xset
            opensuse_add_first_available noto-coloremoji-fonts google-noto-coloremoji-fonts
            opensuse_add_first_available liberation-fonts
            opensuse_add_first_available xorg-x11-fonts

            if [ "${#OPEN_SUSE_PKGS[@]}" -gt 0 ]; then
                sudo zypper --non-interactive install -y "${OPEN_SUSE_PKGS[@]}" || true
            else
                echo "⚠️  No OpenSUSE dependency packages resolved for installation"
            fi
            ;;
    esac
fi

# Check for GitHub SSH reconfiguration flag
GITHUB_SSH_RECONFIG=false
if [[ "${1:-}" == "--github-ssh" ]]; then
    GITHUB_SSH_RECONFIG=true
fi

# Check for Claude settings reconfiguration flag
CLAUDE_RECONFIG=false
if [[ "${1:-}" == "--claude" ]]; then
    CLAUDE_RECONFIG=true
fi

# Check for Claude proxy setup flag
CLAUDE_PROXY_SETUP=false
if [[ "${1:-}" == "--claude-proxy" ]]; then
    CLAUDE_PROXY_SETUP=true
fi

# Check for aliases reconfiguration flag
ALIASES_RECONFIG=false
if [[ "${1:-}" == "--aliases" ]]; then
    ALIASES_RECONFIG=true
fi

# Check for Byobu-only flag
BYOBU_ONLY=false
if [[ "${1:-}" == "--byobu" ]]; then
    BYOBU_ONLY=true
fi

# Check for Tmux-only flag
TMUX_ONLY=false
if [[ "${1:-}" == "--tmux" ]]; then
    TMUX_ONLY=true
fi

# Check for single-script execution: --script SCRIPT_NAME
SCRIPT_ONLY=""
if [[ "${1:-}" == "--script" && -n "${2:-}" ]]; then
    SCRIPT_ONLY="${2}"
fi

echo "🚀 Starting optimized post-configure installation..."

# Create temporary working directory
TEMP_DIR="/tmp/post-configure-$$"
mkdir -p "$TEMP_DIR"
cd "$TEMP_DIR"

# Cleanup function
cleanup() {
    echo "🧹 Cleaning up temporary files..."
    rm -rf "$TEMP_DIR"
}
trap cleanup EXIT

# Download and extract scripts archive
echo "📦 Downloading and extracting scripts..."
SCRIPTS_URL="${POST_CONFIGURE_SCRIPTS_URL:-https://get.chavkov.com/scripts.tar.gz}"
if ! curl -sLSf "${SCRIPTS_URL}" | tar -xzf -; then
    echo "❌ Failed to download or extract scripts archive"
    echo "   Please check your internet connection and try again"
    exit 1
fi
if [ ! -d "./scripts" ]; then
    echo "❌ Failed to extract scripts directory"
    exit 1
fi

# Handle reconfiguration options
if [ "$GITHUB_SSH_RECONFIG" = true ]; then
    echo "🔧 Running GitHub SSH reconfiguration..."
    if [ -f "./scripts/80-github_vchavkov.sh" ]; then
        bash ./scripts/80-github_vchavkov.sh
    elif [ -f "./scripts/81-github_vchavkov82.sh" ]; then
        bash ./scripts/81-github_vchavkov82.sh
    elif [ -f "./scripts/82-github_chv1sf.sh" ]; then
        bash ./scripts/82-github_chv1sf.sh
    elif [ -f "./scripts/83-github_ns9-io.sh" ]; then
        bash ./scripts/83-github_ns9-io.sh
    else
        echo "❌ GitHub SSH configuration scripts not found"
        echo "Available scripts:"
        echo "  - 80-github_vchavkov.sh"
        echo "  - 81-github_vchavkov82.sh"
        echo "  - 82-github_chv1sf.sh"
        echo "  - 83-github_ns9-io.sh"
        exit 1
    fi
elif [ "$CLAUDE_RECONFIG" = true ]; then
    echo "🤖 Running Claude settings reconfiguration..."
    if [ -f "./scripts/22-claude.sh" ]; then
        bash ./scripts/22-claude.sh
    else
        echo "❌ Claude configuration script not found"
        exit 1
    fi
elif [ "$CLAUDE_PROXY_SETUP" = true ]; then
    echo "🤖 Running Claude proxy setup (Bosch LLM Farms)..."
    echo "📥 Downloading claude-proxy.sh..."
    if curl -sLSf https://get.chavkov.com/claude-proxy.sh -o claude-proxy.sh; then
        bash claude-proxy.sh
    else
        echo "❌ Failed to download claude-proxy.sh"
        exit 1
    fi
elif [ "$ALIASES_RECONFIG" = true ]; then
    echo "🔧 Running aliases reconfiguration..."
    if [ -f "./scripts/01-shell-aliases.sh" ]; then
        bash ./scripts/01-shell-aliases.sh
    else
        echo "❌ Aliases configuration script not found"
        exit 1
    fi
elif [ "$BYOBU_ONLY" = true ]; then
    echo "🖥️  Running Byobu setup only..."
    if [ -f "./scripts/18-byobu.sh" ]; then
        bash ./scripts/18-byobu.sh
    else
        echo "❌ Byobu script not found (scripts/18-byobu.sh)"
        exit 1
    fi
elif [ "$TMUX_ONLY" = true ]; then
    echo "🖥️  Running Tmux setup only..."
    if [ -f "./scripts/19-tmux.sh" ]; then
        bash ./scripts/19-tmux.sh
    else
        echo "❌ Tmux script not found (scripts/19-tmux.sh)"
        exit 1
    fi
elif [ -n "$SCRIPT_ONLY" ]; then
    echo "📜 Running single script: $SCRIPT_ONLY"
    # Allow only script basename (no path traversal)
    case "$SCRIPT_ONLY" in
        */*) echo "❌ Invalid script name (no path allowed): $SCRIPT_ONLY"; exit 1 ;;
    esac
    if [ -f "./scripts/$SCRIPT_ONLY" ]; then
        bash "./scripts/$SCRIPT_ONLY"
    else
        echo "❌ Script not found: scripts/$SCRIPT_ONLY"
        exit 1
    fi
else
    # Execute the run-scripts.sh from the extracted archive
    echo "🔧 Running installation scripts..."
    bash ./scripts/run-scripts.sh
fi

echo "✅ Installation completed!"
