#!/usr/bin/env bash

set -euo pipefail

REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TRACKED_CONFIGS="$REPO_DIR/tracked-configs.txt"

copy_path() {
    local source="$1"
    local destination="$2"

    if [[ ! -e "$source" && ! -L "$source" ]]; then
        echo "Skipping missing source: $source"
        return 0
    fi

    if [[ -e "$destination" || -L "$destination" ]]; then
        if [[ "$(readlink -f "$source")" == "$(readlink -f "$destination")" ]]; then
            echo "Already tracked: ${destination#$REPO_DIR/}"
            return 0
        fi
        rm -rf "$destination"
    fi

    mkdir -p "$(dirname "$destination")"
    cp -a "$source" "$destination"
    echo "Copied $source -> ${destination#$REPO_DIR/}"
}

read_list() {
    local file="$1"

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

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

write_version_file() {
    {
        echo "Generated: $(date -Is)"
        echo "Kernel: $(uname -r)"
        if command -v hyprctl >/dev/null 2>&1; then
            hyprctl version | sed -n '1p' | sed 's/^/Hyprland: /'
        fi
        if command -v omarchy >/dev/null 2>&1; then
            omarchy version 2>/dev/null | sed 's/^/Omarchy: /' || true
        fi
    } > "$REPO_DIR/version.txt"
}

cd "$REPO_DIR"

echo "Updating package lists..."

pacman -Qqe > packages.txt
pacman -Qqem > aur-packages.txt
pacman -Qe > installed-packages-full.txt

if command -v flatpak >/dev/null 2>&1; then
    flatpak list --app --columns=application > flatpaks.txt
fi

echo "Updating version info..."
write_version_file

echo "Updating tracked configs..."

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

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

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

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

    copy_path "$source" "$destination"
done < "$TRACKED_CONFIGS"

echo "Updating scripts, launchers, and fonts..."

if [[ -d "$HOME/.local/bin" ]]; then
    mkdir -p scripts
fi

if [[ -d "$HOME/.local/share/applications" ]]; then
    mkdir -p applications
fi

if [[ -d "$HOME/.local/share/fonts/omarchy-config" ]]; then
    copy_path "$HOME/.local/share/fonts/omarchy-config" "$REPO_DIR/fonts"
fi

echo "Updating services..."

systemctl --user list-unit-files --state=enabled > system/user-services.txt

if command -v sudo >/dev/null 2>&1; then
    sudo -n systemctl list-unit-files --state=enabled > system/system-services.txt 2>/dev/null || true
fi

echo
echo "Done!"
echo
echo "Review changes:"
echo "git diff"
