dotfiles/use_nix.sh
2025-10-13 14:25:15 +02:00

78 lines
2.0 KiB
Bash

#!/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 " --rebuild Automatically run nixos-rebuild after copying files"
echo " --upgrade Upgrade installed packages to match flake.lock"
echo " --re-flake Delete the flake.lock, forcing to fetch the latest in-branch commits"
}
AUTO_REBUILD=0
UPGRADE=0
RE_FLAKE=0
# Parse arguments
for arg in "$@"; do
case $arg in
--rebuild) AUTO_REBUILD=1 ;;
--upgrade) UPGRADE=1 ;;
--re-flake) RE_FLAKE=1 ;;
--help|-h) show_usage; exit 0 ;;
*) echo "Unknown option: $arg"; show_usage; exit 1 ;;
esac
done
check_root
# Check if source directory exists
if [[ ! -d "root-conf/nixos" ]]; then
echo "Error: Source directory 'root-conf/nixos' not found!" >&2
exit 1
fi
# 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/
ls -l /etc/nixos/
if [[ $RE_FLAKE -eq 1 ]]; then
echo "Deleting flake.lock to update in given channel"
rm /etc/nixos/flake.lock 2>/dev/null || true
fi
# Rebuild if requested
if [[ $AUTO_REBUILD -eq 1 ]]; then
echo "Running nixos-rebuild switch..."
if [[ $UPGRADE -eq 1 ]]; then
echo "First run: running nixos-rebuild with --upgrade"
nixos-rebuild switch --upgrade
else
echo "Running nixos-rebuild switch with flake"
nixos-rebuild switch --flake /etc/nixos
fi
cp /etc/nixos/flake.lock root-conf/nixos/flake.lock
fi
echo "Done!"