#!/usr/bin/env bash

# Nomarchy Environment Update Script
# Standalone Home Manager iteration path. Use this for fast dotfile and
# theme changes that don't need a full system rebuild. For first-boot
# dotfiles and any system-level change, the NixOS module activation
# from `sudo nixos-rebuild switch` is the source of truth.

set -e

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

if command -v nomarchy-preflight-migration >/dev/null 2>&1; then
    nomarchy-preflight-migration
fi

echo "Applying user-level changes from $REPO_DIR#$USER..."
if command -v home-manager >/dev/null 2>&1; then
    home-manager switch --flake "$REPO_DIR#$USER" --impure
else
    # Bootstrap path: HM hasn't put `home-manager` on PATH yet (e.g. running
    # straight after a partial install). Pull it from the flake registry.
    nix --extra-experimental-features 'nix-command flakes' \
        run 'home-manager/release-25.11' \
        -- switch --flake "$REPO_DIR#$USER" --impure
fi

echo "Environment update complete."
