#!/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|-b] [flake-uri#]name"
    echo "Build a NixOS configuration on the local machine."
    echo
    echo "Arguments:"
    echo "  profile: OS/disk profile to use"
    echo
    echo "Options:"
    echo "  -h: Display this help message."
    echo "  -v: Build a virtual machine."
    echo "  -b: Build a virtual machine with boot loader."
}

arg=build
while getopts "hvb" OPTION
do
    case "$OPTION" in
        h)
            help
            exit 0
            ;;
        v)
            arg=build-vm
            ;;
        b)
            arg=build-vm-with-bootloader
            ;;
        ?)
            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}"

set -x

nix --extra-experimental-features "nix-command flakes" run "${SCRIPT_DIR}#nixos-rebuild" -- "$arg" --flake "$flake"

echo 

# TODO Use update-local-flakes?