#!/usr/bin/env nix-shell
#! nix-shell -i bash
#! nix-shell -p nix

set -euo pipefail
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

# Parse arguments
function help {
    echo "Usage: $0 [-h|-e] [flake-uri#]name"
    echo "Install a NixOS configuration from another installation on the same machine."
    echo
    echo "Arguments:"
    echo "  flake-uri: Path to flake containing the system configuration. Default: the one where the script is located."
    echo "  name:      Hostname of the configuration to install. The flake must contain an output named 'nixosConfigurations.*name*'"
    echo
    echo "Options:"
    echo "  -h: Display this help message."
    echo "  -e: Erase the disk. For cases where the partition scheme doesn't match the existing one."
}

disko_mode=mount
while getopts "he" OPTION
do
    case "$OPTION" in
        h)
            help
            exit 0
            ;;
        e)
            disko_mode=disko
            ;;
        ?)
            help
            exit 2
            ;;
    esac
done
shift "$((OPTIND -1))"

if [ "$#" -ne 1 ]
then
    help
    exit 2
fi

if [[ "$1" == *"#"* ]]
then
    flake_uri="$(echo "$1" | cut -d'#' -f1)"
    flake_uri=$( cd -- "$flake_uri" &> /dev/null && pwd )
    name="$(echo "$1" | cut -d'#' -f2)"
else
    flake_uri="$SCRIPT_DIR"
    name="$1"
fi

if [ ! -f "$flake_uri/flake.nix" ]
then
    echo "Flake not found."
fi

flake="${flake_uri}#${name}"
mountpoint="/mnt/nixos"
luks_pass_path="luks/$(basename "${name}")"

set -x

sudo mkdir -p "$mountpoint"

# Load encryption password
luks_pass_file="/tmp/dotfiles_${name}_password";
trap 'rm "$luks_pass_file"' ERR
touch "$luks_pass_file"
chmod "u=rw" "$luks_pass_file"
pass "$luks_pass_path" | head -n1 | tr -d '\n' > "$luks_pass_file"

# Format or mount disk
sudo nix --extra-experimental-features "nix-command flakes" run "${SCRIPT_DIR}#disko" -- --mode "$disko_mode" --flake "$flake"
# --root-mountpoint is ignored with flakes, so this is set in os/common.nix

# Unload encryption password
trap - ERR
rm "$luks_pass_file"

# Save that system configuration uses this repo
sudo mkdir -p "${mountpoint}/etc"
sudo ln -sfn "${flake_uri}" "${mountpoint}/nixos"

# Install NixOS! Or create a new generation.
sudo nix --extra-experimental-features "nix-command flakes" run "${SCRIPT_DIR}#nixos-install" -- --no-root-password --root "$mountpoint" --flake "$flake"

set +x

# Signal the installation is done!
echo 

echo "Manual post-installation instructions:"
echo "- Boot into the system"
echo "- Transfer necessary private keys (or use ssh -A for testing)"
echo "- Run git-sync"
echo "- Run install-passwords"
echo "- Run install-wifi"
echo "- Run rb"
echo "- Change root and user password"

# TODO Use update-local-flakes?