#!/usr/bin/env bash

# GNU GPL v3 2025 K9BFF

su_check() {
	if [[ $EUID -ne 0 ]]; then
		echo "sysop: needs to be run as sudo..."
		exit 1
	fi
}

inv_su_check() {
	if [[ $EUID -eq 0 ]]; then
		echo "sysop: don't run this flag as sudo!"
		exit 1
	fi
}

if [[ $1 == "-r" ]]; then
	su_check
	update-dotfiles
	nixos-rebuild switch |& nom

elif [[ $1 == "-u" ]]; then
	su_check
	nixos-rebuild switch --upgrade |& nom

elif [[ $1 == "-d" ]]; then
	su_check
	read -p "sysop: garbage collection: are you sure? (y/N): " yesno
	if [[ ${yesno:0:1} == "y" ]]; then
		nix-collect-garbage -d |& nom
	else
		echo "sysop: couldn't confirm..."
		exit 1
	fi

elif [[ $1 == "-p" ]]; then
	inv_su_check
	nix-shell -p "$2" |& nom

elif [[ $1 == "-s" ]]; then
	inv_su_check
	nix-search "$2"

elif [[ $1 == "-h" ]]; then
	echo "sysop: system operations"
	echo
	echo "flag   operation"
	echo "-r     Rebuild"
	echo "-u     Upgrade"
	echo "-d     Garbage Collection"
	echo "-p     nix-shell install (temporary)"
	echo "-s     Search"
	echo "-h     Display this help"

else
	echo "sysop: $1: not a valid flag. Please see sysop -h for more information."
	exit 1
fi
