#!/usr/bin/env bash
set -euo pipefail

#echo "searching generations"
# your hostname (flake target)
hostname="$(hostname)"
#old_gen=$(nixos-rebuild list-generations | grep current | awk '{print $1}')
#gen=$((old_gen + 1))
#echo "gen $old_gen --> gen $gen"
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
nix_dir="$HOME/.nix"
logfile="$nix_dir/.nixos-switch-log"


pushd "$nix_dir" >/dev/null

# function to get current nixos generation
#get_current_generation() {
#    nixos-rebuild list-generations
#}

echo "diffs:"
git diff
echo ""
echo "files:"
git status --short
read -rp "commit message: " commit_msg
echo "rebuilding nixos with flake.nix..."
if ! sudo nixos-rebuild switch --flake .#"$hostname" 2>&1 | tee "$logfile"; then
    echo "rebuild failed; exited with no commit"
    exit 1
fi
#if sed -n '3p' flake.nix | grep -q '^# generation:'; then
#    # replace the comment on line 3
#    sed -i "3s|^# generation:.*|# generation: $gen, timestamp: $timestamp|" flake.nix
#else
#    # insert comment on line 3
#    sed -i "3i# generation: $gen, timestamp: $timestamp" flake.nix
#fi
echo "committing..."
git add $nix_dir 
git commit -m "$commit_msg"
echo "flake rebuild and commit fin"

