#!/usr/bin/env bash

set -euo 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)"

echo "========================================"
echo " Milan's Omarchy Setup Installer"
echo "========================================"
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"

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

    yay -S --needed --noconfirm "${packages[@]}"
}

echo "[1/8] Updating system..."
yay -Syu --noconfirm

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

if [[ -s "$REPO_DIR/flatpaks.txt" ]] && command -v flatpak >/dev/null 2>&1; then
    while read -r app; do
        [[ -n "$app" ]] || continue
        flatpak install --user --noninteractive flathub "$app" || true
    done < <(read_list "$REPO_DIR/flatpaks.txt")
fi

echo
echo "[3/8] 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 "[4/8] 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 "[5/8] 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 "[6/8] Linking fonts..."

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

echo
echo "[7/8] Enabling user 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 || true
    done
fi

if [[ -f "$REPO_DIR/system/system-services.txt" ]]; then
    if [[ "${ENABLE_SYSTEM_SERVICES:-0}" == "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 || true
            fi
        done
    else
        echo "Skipping system services. Run with ENABLE_SYSTEM_SERVICES=1 to enable them."
    fi
fi

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

if [[ -x "$REPO_DIR/smb/install.sh" ]]; then
    if [[ "${INSTALL_SMB:-0}" == "1" ]]; then
        "$REPO_DIR/smb/install.sh"
    else
        echo "Skipping SMB installer. Run with INSTALL_SMB=1 to enable it."
    fi
fi

echo
echo "========================================"
echo " Finished!"
echo "========================================"
echo
echo "Backups were written to: $BACKUP_DIR"
echo
echo "You may want to log out and back in, or restart Waybar/Hyprland if configs changed."
echo
