#!/usr/bin/env bash

set -euo pipefail

REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIGS_DIR="$REPO_DIR/configs"

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

#
# Update system
#
echo "[1/5] Updating system..."
yay -Syu --noconfirm

#
# Install packages
#
echo
echo "[2/5] Installing packages..."

if [[ -f "$REPO_DIR/packages.txt" ]]; then
    yay -S --needed --noconfirm $(<"$REPO_DIR/packages.txt")
fi

if [[ -s "$REPO_DIR/aur-packages.txt" ]]; then
    yay -S --needed --noconfirm $(<"$REPO_DIR/aur-packages.txt")
fi

#
# Symlink configs
#
echo
echo "[3/5] Linking configs..."

mkdir -p "$HOME/.config"

for item in "$CONFIGS_DIR"/*; do

    name="$(basename "$item")"

    target="$HOME/.config/$name"

    # Skip if already linked correctly
    if [[ -L "$target" ]]; then
        if [[ "$(readlink -f "$target")" == "$(readlink -f "$item")" ]]; then
            echo "✓ $name already linked"
            continue
        fi
    fi

    # Backup existing config
    if [[ -e "$target" && ! -L "$target" ]]; then
        backup="${target}.backup.$(date +%Y%m%d-%H%M%S)"
        echo "Backing up $name -> $(basename "$backup")"
        mv "$target" "$backup"
    fi

    rm -rf "$target"

    ln -s "$item" "$target"

    echo "Linked $name"

done

#
# Enable user services
#
echo
echo "[4/5] Enabling user services..."

if [[ -f "$REPO_DIR/system/user-services.txt" ]]; then
    awk '{print $1}' "$REPO_DIR/system/user-services.txt" |
    while read -r service; do
        [[ -z "$service" ]] && continue
        systemctl --user enable "$service" >/dev/null 2>&1 || true
    done
fi

#
# Font cache
#
echo
echo "[5/5] Refreshing font cache..."
fc-cache -fv >/dev/null 2>&1 || true

echo
echo "========================================"
echo " Finished!"
echo "========================================"
echo
echo "You may want to:"
echo "  • Log out and back in"
echo "  • Run: omarchy-theme (if needed)"
echo "  • Restart Waybar/Hyprland if configs changed"
echo
