#!/usr/bin/env bash
pushd /etc/nixos/git

# Home-Manager Setup
echo ">>> Setting up Home Manager..... "
sudo mkdir /nix/var/nix/profiles/per-user/albert
sudo chown -R albert:root /nix/var/nix/profiles/per-user/albert
home-manager switch -b backup --flake /etc/nixos/git
source ~/.bashrc

# Import and trust the GPG key
echo ">>> Setting up user GPG key..... "
drive=$(lsblk -o serial,name | grep NGN130R000980P2202 | awk {'print $2'})
sudo mkdir -p /tmp/drive
sudo cryptsetup luksOpen /dev/${drive}3 usb-luks
sudo mount /dev/mapper/usb-luks /tmp/drive
gpg --import /tmp/drive/gpg/albert@sysctl.io/privkey.asc
sudo umount /tmp/drive
sudo rmdir /tmp/drive
sudo cryptsetup luksClose /dev/mapper/usb-luks
echo -e "5\ny\n" |  gpg --command-fd 0 --expert --edit-key albert@sysctl.io trust

# Setup SOPS
echo "Setting up SOPS keys..... "
echo ">>> !!!!!"
echo ">>> !!!!!"
echo ">>> !!!!!"
echo ">>> !!!!! Copy this signature to .sops.yaml:  "
echo ">>> !!!!!"
echo ">>> !!!!!"
echo ">>> !!!!!"

# Currently only RSA keys are allowed
sudo ssh-to-pgp \
    -comment "Generated `date +%Y.%m.%d`" \
    -email "root@`hostname`" \
    -i /etc/ssh/ssh_host_rsa_key \
    -o /etc/nixos/git/keys/hosts/$(hostname).asc

# Set up ssh keys
echo ">>> Setting up SSH Keys..... "
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519  -N ""
echo "" >> ./keys/ssh/keys.txt
echo "# (`date`) `whoami`@`hostname`" >> ./keys/ssh/keys.txt
cat /home/albert/.ssh/id_ed25519.pub >> ./keys/ssh/keys.txt

# echo ">>> Setting up Distributed Build SSH Keys..... "
# sudo ssh-keygen -t ed25519 -f /root/.ssh/id_ed25519 -N ""
# echo "" >> ./keys/ssh/builder-keys.txt
# echo "# (`date`) root@`hostname`" >> ./keys/ssh/builder-keys.txt
# sudo cat /root/.ssh/id_ed25519.pub >> ./keys/ssh/builder-keys.txt

# Add all changes to git and and push
echo ">>> Pushing to git..... "
git add keys/hosts/`hostname`.asc
git commit -am "Setup: `hostname`"
git push

echo
echo
echo ">>> Complete.  Once '.sops.yaml' is updated, "
echo ">>> run 'update-secrets' and reboot."
echo 
echo
echo ">>> Reminder:  Upload these changes to git"

popd