#!/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

# 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

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 ---"
