#!/usr/bin/env bash

# Nomarchy Update Script
# 1. Updates the flake inputs in the repository
# 2. Applies system-wide NixOS changes
# 3. Applies user-level Home Manager changes (Standalone)

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 Update from $REPO_DIR ---"

# 1. Update Flake Lock
echo "Updating flake inputs..."
sudo nix flake update --flake "$REPO_DIR"

# 2. Rebuild System
echo "Applying system-level updates..."
sudo nixos-rebuild switch --flake "$REPO_DIR#default" --impure

# 3. Rebuild Home Environment (Standalone)
echo "Applying user-level updates..."
home-manager switch --flake "$REPO_DIR#$USER" --impure

# 4. Commit changes if it's a git repo
if [ -d "$REPO_DIR/.git" ]; then
    echo "Committing update to local history..."
    sudo git -C "$REPO_DIR" add flake.lock
    sudo git -C "$REPO_DIR" commit -m "chore: update system (flake.lock)" || echo "No lockfile changes to commit."
fi

echo "--- Nomarchy Update Complete ---"
