#!/usr/bin/env bash set -e # use_nix.sh - Script to update NixOS configuration # Usage: use_nix.sh [--rebuild] [--upgrade] [--re-flake] function check_root() { if [[ $EUID -ne 0 ]]; then echo "This script must be run as root" >&2 exit 1 fi } function show_usage() { echo "Usage: $0 [--rebuild] [--upgrade] [--re-flake]" echo " --no-rebuild Disable automatic run of nixos-rebuild after copying files" echo " --upgrade Upgrade installed packages to match flake.lock" echo " --update [inputs] Update the flake.lock file to latest" echo " --re-flake Delete the flake.lock, forcing to fetch the latest in-branch commits" } AUTO_REBUILD=1 UPGRADE=0 RE_FLAKE=0 UPDATE=0 FLAKES_TO_UPDATE=() # Parse arguments prev_arg="" for arg in "$@"; do case $arg in --no-rebuild) AUTO_REBUILD=0 ;; --upgrade) UPGRADE=1 ;; --update) UPDATE=1 ;; --re-flake) RE_FLAKE=1 ;; --help|-h) show_usage; exit 0 ;; *) if [ "${arg:0:2}" != "--" ]; then case $prev_arg in --update) FLAKES_TO_UPDATE+=($arg) ;; *) echo "No argument needet for: $prev_arg"; show_usage; exit 1 ;; esac continue fi; echo "Unknown option: $arg"; show_usage; exit 1 ;; esac prev_arg=$arg done # Check if source directory exists if [[ ! -d "root-conf/nixos" ]]; then echo "Error: Source directory 'root-conf/nixos' not found!" >&2 exit 1 fi if [[ $UPDATE -eq 1 ]]; then echo "Updatening flake.lock $FLAKES_TO_UPDATE" cd root-conf/nixos nix flake update $FLAKES_TO_UPDATE cd - fi check_root # Backup existing configuration if [[ -d /etc/nixos ]]; then echo "Backing up existing configuration to /etc/nixos.bak" rm -rf /etc/nixos.bak 2>/dev/null || true cp -r /etc/nixos /etc/nixos.bak rm -rf /etc/nixos/* else mkdir -p /etc/nixos fi # Copy new configuration echo "Copying files to /etc/nixos/" cp -r root-conf/nixos/* /etc/nixos/ if [[ $RE_FLAKE -eq 1 ]]; then echo "Deleting flake.lock" rm /etc/nixos/flake.lock 2>/dev/null || true rm root-conf/nixos/flake.lock 2>/dev/null || true fi ARGS="" if [[ $AUTO_REBUILD -eq 1 ]]; then ARGS+="switch " else ARGS+="boot " fi if [[ $UPGRADE -eq 1 ]]; then ARGS+="--upgrade " fi ARGS+="--flake /etc/nixos" echo "Running: nixos-rebuild $ARGS" nixos-rebuild $ARGS cp /etc/nixos/flake.lock root-conf/nixos/flake.lock diff -r /etc/nixos.bak root-conf/nixos | colordiff --nobanner echo "Done!"