#!/bin/sh
# Bootstrap
set -e
ROOT_FOLDER=$(realpath $0 | xargs dirname)
. $ROOT_FOLDER/common.sh
# Bootstrap

# export NIX_SSHOPTS="-o RequestTTY=force"

target=${1}
target_host=root@$target.lab.internal
profile=hl-$target

valid_profiles=$(nix flake show --json 2> /dev/null | jq -r -c '.nixosConfigurations | keys[]' | grep "hl")

function print_valid_targets {
    echo "valid targets:"
    while IFS= read -r line; do
        echo $line | sed -r 's/.*hl-/ - /g'
    done <<< "$valid_profiles"
}

if [ -z $target ]; then
    echo "must specify a target!"
    print_valid_targets
    exit 1
fi

if echo "$valid_profiles" | grep -qFx "$profile"; then
    echo "Using [$profile]"
else
    echo "Invalid target! '$profile'"
    print_valid_targets
    exit 1
fi

function run {
    remote_cmd=${1}
    echo -e "$BOLD$remote_cmd$NC on $YELLOW$target_host with $profile through $build_host$NC"
    runcmd="nixos-rebuild --target-host $target_host --use-remote-sudo $remote_cmd --flake .#$profile"
    echo -e "$BLUE$runcmd$NC"
    $runcmd 
}

cmd=${2}
case $cmd in
    "test" | "dry-activate" | "run" | "switch" | "build") run $cmd;;
    *) 
        echo "invalid command"
        exit 1
        ;;
esac
