#!/usr/bin/env bash
set -e
pushd ~/.nix
# nvim flake.nix
# alejandra . &>/dev/null
# git diff -U0 *.nix

# add generation comment to flake.nix
gen=$(nixos-rebuild list-generations | grep current)
if sed -n '3p' flake.nix | grep -q '^# generation:'; then
    # replace the comment on line 3
    sed -i "3s/^# generation:.*/# generation: $gen/" flake.nix
else
    # insert comment on line 3
    sed -i "3i# generation: $gen" flake.nix
fi

git diff -U0 $(find . -name '*.nix')

echo "nixos rebuilding..."
#sudo nixos-rebuild switch --flake ~/.nix#snowbelle &>.nixos-switch-log || (
# cat .nixos-switch-log | grep --color error && false)
sudo nixos-rebuild switch --flake ~/.nix#snowbelle 2>&1 | tee .nixos-switch-log | grep --color=always -E "error|$" && true

git commit -am "$gen"
popd
