#!/usr/bin/env bash

# Nomarchy System Update Script
# 1. Applies system-wide NixOS changes

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

# The installer generates `nixosConfigurations.<hostname>` (see
# installer/install.sh: `nixosConfigurations.$HOSTNAME`), so the flake target
# must match the current host. The previous `#default` literal worked only
# for a development host that happened to be named "default" and silently
# broke every toggle script (nomarchy-tz-select, nomarchy-wifi-powersave,
# nomarchy-setup-{dns,fido2,fingerprint}, nomarchy-toggle-hybrid-gpu) on a
# real install.
HOSTNAME_ATTR=$(hostname)
if [ -z "$HOSTNAME_ATTR" ]; then
    echo "Error: could not determine hostname for flake attribute." >&2
    exit 1
fi

echo "Applying system-level changes from $REPO_DIR#$HOSTNAME_ATTR..."
sudo nixos-rebuild switch --flake "$REPO_DIR#$HOSTNAME_ATTR"

echo "System update complete."
