#!/usr/bin/env bash

# Nomarchy Full Update Script
# 1. Removes the installation pin (if present) to follow the rolling release.
# 2. Updates flake inputs (Nomarchy, nixpkgs, etc.) in flake.lock.
# 3. Performs a full system update (NixOS + Home Manager)

set -e

# Fast fail offline check for gum
if ! ping -c 1 -W 2 1.1.1.1 >/dev/null 2>&1; then
    if command -v gum >/dev/null 2>&1; then
        gum style --foreground 196 "You are offline. Cannot update."
        sleep 3
    else
        echo "You are offline. Cannot update."
    fi
    exit 1
fi

# Detect the repository location
if [ -f "/etc/nixos/flake.nix" ]; then
    REPO_DIR="/etc/nixos"
elif [ -f "/etc/nomarchy/flake.nix" ]; then
    REPO_DIR="/etc/nomarchy"
else
    echo "Error: Nomarchy flake repository not found in /etc/nixos or /etc/nomarchy."
    exit 1
fi

CURRENT_REV=$(jq -r '.nodes.nomarchy.locked.rev // empty' "$REPO_DIR/flake.lock" 2>/dev/null)
REMOTE_URL="https://git.bemagri.xyz/bernardo/Nomarchy.git"
LATEST_REV=$(git ls-remote "$REMOTE_URL" HEAD 2>/dev/null | awk '{print $1}')

if command -v gum >/dev/null 2>&1; then
    gum style --foreground 212 --border double --margin "1 2" --padding "1 2" "Nomarchy System Update"
    
    if [[ "$CURRENT_REV" != "$LATEST_REV" && -n "$LATEST_REV" ]]; then
        echo -e "An update for Nomarchy is available!\n"
        echo -e "Current Revision: ${CURRENT_REV:0:7}"
        echo -e "Latest Revision:  ${LATEST_REV:0:7}\n"
        
        if ! gum confirm "Do you want to download and apply the update now?"; then
            echo "Update cancelled."
            sleep 2
            exit 0
        fi
    else
        echo -e "\nYou are already up to date! (${CURRENT_REV:0:7})"
        if ! gum confirm "Do you want to force a system rebuild anyway?"; then
            echo "Cancelled."
            sleep 2
            exit 0
        fi
    fi
fi

echo "--- Starting Nomarchy Full Update ---"

# 1. Unpin the flake if it's currently pinned to the install commit
if grep -q "rev=" "$REPO_DIR/flake.nix"; then
    echo "Removing installation pin to follow rolling release..."
    sudo sed -i 's/?rev=[a-f0-9]*//g' "$REPO_DIR/flake.nix"
fi

# 2. Update flake inputs
echo "Updating flake inputs (this may take a moment)..."
sudo nix --extra-experimental-features 'nix-command flakes' flake update --flake "$REPO_DIR"

# 3. System update
nomarchy-sys-update

echo "--- Nomarchy Full Update Complete ---"
if command -v gum >/dev/null 2>&1; then
    echo ""
    gum style --foreground 82 "Update Applied Successfully!"
    echo "Press any key to exit."
    read -n 1 -s -r
fi
