#!/usr/bin/env bash

set -uo pipefail

REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TRACKED_CONFIGS="$REPO_DIR/tracked-configs.txt"
BACKUP_DIR="$HOME/.local/state/omarchy-config/backups/$(date +%Y%m%d-%H%M%S)"

# Configuration
UPDATE_SYSTEM="${UPDATE_SYSTEM:-0}"
ENABLE_SYSTEM_SERVICES="${ENABLE_SYSTEM_SERVICES:-0}"
INSTALL_SMB="${INSTALL_SMB:-0}"

echo "========================================"
echo " Milan's Omarchy Setup Installer"
echo "========================================"
echo

# Step 0: Verify required commands
echo "[0/9] Verifying required commands..."

required_commands=("yay" "git" "systemctl" "fc-cache" "flatpak")

for cmd in "${required_commands[@]}"; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
        echo "ERROR: Required command not found: $cmd"
        exit 1
    fi
done

echo "All required commands are available."
echo

ensure_dir() {
    mkdir -p "$1"
}

read_list() {
    local file="$1"

    [[ -f "$file" ]] || return 0

    sed 's/#.*//' "$file" | awk 'NF {print $1}'
}

backup_target() {
    local target="$1"
    local backup

    [[ -e "$target" || -L "$target" ]] || return 0

    ensure_dir "$BACKUP_DIR"
    backup="$BACKUP_DIR/${target#$HOME/}"
    ensure_dir "$(dirname "$backup")"

    echo "Backing up $target"
    mv "$target" "$backup"
}

link_path() {
    local source="$1"
    local target="$2"

    if [[ ! -e "$source" ]]; then
        echo "Skipping missing source: ${source#$REPO_DIR/}"
        return 0
    fi

    ensure_dir "$(dirname "$target")"

    if [[ -L "$target" && "$(readlink -f "$target")" == "$(readlink -f "$source")" ]]; then
        echo "Already linked: $target"
        return 0
    fi

    backup_target "$target"
    ln -s "$source" "$target"
    echo "Linked $target -> ${source#$REPO_DIR/}"
}

install_packages() {
    local file="$1"
    local failed_packages=()

    [[ -s "$file" ]] || return 0
    mapfile -t packages < <(read_list "$file")
    ((${#packages[@]} > 0)) || return 0

    # Install packages individually
    for pkg in "${packages[@]}"; do
        [[ -n "$pkg" ]] || continue
        if ! yay -S --needed --noconfirm "$pkg" 2>/dev/null; then
            failed_packages+=("$pkg")
        fi
    done

    # Report failures if any
    if (( ${#failed_packages[@]} > 0 )); then
        echo "WARNING: Failed to install ${#failed_packages[@]} package(s) from $file:"
        printf "  - %s\n" "${failed_packages[@]}"
        return 0  # Don't abort, continue with other installation steps
    fi
}

install_flatpaks() {
    local file="$1"
    local failed_apps=()

    [[ -s "$file" ]] || return 0

    # Check if Flathub remote exists
    if ! flatpak remote-list 2>/dev/null | grep -q "flathub"; then
        echo "Adding Flathub remote..."
        flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo || {
            echo "WARNING: Failed to add Flathub remote, skipping Flatpak installation"
            return 0
        }
    fi

    # Install Flatpak apps individually
    while read -r app; do
        [[ -n "$app" ]] || continue
        if ! flatpak install --user --noninteractive flathub "$app" 2>/dev/null; then
            failed_apps+=("$app")
        fi
    done < <(read_list "$file")

    # Report failures if any
    if (( ${#failed_apps[@]} > 0 )); then
        echo "WARNING: Failed to install ${#failed_apps[@]} Flatpak app(s):"
        printf "  - %s\n" "${failed_apps[@]}"
    fi
}

echo "[1/9] Checking system update status..."
if [[ "$UPDATE_SYSTEM" == "1" ]]; then
    echo "Updating system (UPDATE_SYSTEM=1)..."
    yay -Syu --noconfirm
else
    echo "Skipping system update (run with UPDATE_SYSTEM=1 to enable)"
fi

echo
echo "[2/9] Installing packages..."
install_packages "$REPO_DIR/packages.txt"
install_packages "$REPO_DIR/aur-packages.txt"

echo
echo "[3/9] Installing Flatpak applications..."
if command -v flatpak >/dev/null 2>&1; then
    install_flatpaks "$REPO_DIR/flatpaks.txt"
else
    echo "Flatpak not found, skipping Flatpak installation"
fi

echo
echo "[4/9] Linking tracked configs..."

if [[ ! -f "$TRACKED_CONFIGS" ]]; then
    echo "Missing tracked-configs.txt"
    exit 1
fi

while read -r source target; do
    [[ -n "${source:-}" ]] || continue
    [[ "$source" != \#* ]] || continue
    [[ -n "${target:-}" ]] || target="$source"

    source="${source/#\~/$HOME}"
    target="${target/#\~/$HOME}"

    [[ "$source" = /* ]] || source="$REPO_DIR/$source"
    [[ "$target" = /* ]] || target="$HOME/$target"

    link_path "$source" "$target"
done < "$TRACKED_CONFIGS"

echo
echo "[5/9] Linking scripts..."

if [[ -d "$REPO_DIR/scripts" ]]; then
    ensure_dir "$HOME/.local/bin"
    find "$REPO_DIR/scripts" -maxdepth 1 -type f -executable | sort |
    while read -r script; do
        link_path "$script" "$HOME/.local/bin/$(basename "$script")"
    done
fi

echo
echo "[6/9] Linking desktop launchers..."

if [[ -d "$REPO_DIR/applications" ]]; then
    ensure_dir "$HOME/.local/share/applications"
    find "$REPO_DIR/applications" -maxdepth 1 -type f -name '*.desktop' | sort |
    while read -r launcher; do
        link_path "$launcher" "$HOME/.local/share/applications/$(basename "$launcher")"
    done
fi

echo
echo "[7/9] Setting up fonts..."

if [[ -d "$REPO_DIR/fonts" ]]; then
    ensure_dir "$HOME/.local/share/fonts"
    link_path "$REPO_DIR/fonts" "$HOME/.local/share/fonts/omarchy-config"
    echo "Running font cache update..."
    fc-cache -fv >/dev/null 2>&1 || true
fi

echo
echo "[8/9] Enabling services..."

if [[ -f "$REPO_DIR/system/user-services.txt" ]]; then
    read_list "$REPO_DIR/system/user-services.txt" |
    while read -r service; do
        systemctl --user enable "$service" >/dev/null 2>&1 || {
            echo "WARNING: Failed to enable user service: $service"
        }
    done
fi

if [[ -f "$REPO_DIR/system/system-services.txt" ]]; then
    if [[ "$ENABLE_SYSTEM_SERVICES" == "1" ]]; then
        read_list "$REPO_DIR/system/system-services.txt" |
        while read -r service; do
            if systemctl list-unit-files "$service" >/dev/null 2>&1; then
                sudo systemctl enable "$service" >/dev/null 2>&1 || {
                    echo "WARNING: Failed to enable system service: $service"
                }
            else
                echo "WARNING: System service not found: $service"
            fi
        done
    else
        echo "Skipping system services (run with ENABLE_SYSTEM_SERVICES=1 to enable)"
    fi
fi

echo
echo "[9/9] Running optional installers..."

if [[ -x "$REPO_DIR/smb/install.sh" ]]; then
    if [[ "$INSTALL_SMB" == "1" ]]; then
        "$REPO_DIR/smb/install.sh"
    else
        echo "Skipping SMB installer (run with INSTALL_SMB=1 to enable)"
    fi
fi

echo
echo "========================================"
echo " Installation Complete!"
echo "========================================"
echo
if [[ -d "$BACKUP_DIR" && -n "$(find "$BACKUP_DIR" -type f 2>/dev/null)" ]]; then
    echo "Backups were written to: $BACKUP_DIR"
    echo
fi
echo "You may want to log out and back in, or restart Waybar/Hyprland if configs changed."
echo
