#!/usr/bin/env bash
set -e


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

MENAME=$(basename $0)
LOCKS_FOLDER=/tmp/skyg/$ROOT_FOLDER/.tmp/.locks
LOCK_FILE=$LOCKS_FOLDER/.built_via_skg

mkdir -p $LOCKS_FOLDER

function lock() {
    touch $LOCK_FILE
}
function unlock() {
    rm -f $LOCK_FILE
}

function run-build() {
    : Run nixos build and emits difference
    :
    unlock
    echo "sudo nixos-rebuild build --flake ."
    sudo nixos-rebuild build --flake .
    lock
    run-diff
}

function run-switch() {
    : Runs nixos switch and ensures that we actually saw a build\'s difference
    :
    if [ ! -f $LOCK_FILE ]; then
        run-build
        echo "Do you want to continue? (y/N)"
        read -r answer
        if [[ $answer =~ ^[yY]$ ]]; then
            echo "Continuing..."
        else
            echo "Exiting."
            exit 1
        fi
    fi
    
    sudo nixos-rebuild switch --flake .
    unlock
    
}

function run-rollback() {
    : Rolls back to last configuration
    :
    sudo nixos-rebuild switch --rollback
}

function run-update() {
    : Updates a single flake and runs update
    :  Usage: skyg update {name-of-input}
    input_name=${1}
    if [ ! -z $input_name ]; then
        cmd="nix flake lock --update-input $input_name"
    else
        cmd="nix flake update"
    fi
    echo $cmd
    $cmd
}

function run-diff() {
    : Diff results to current system
    :
    echo -e "Running ${YELLOW_BOLD}nvd${NC}"
    sudo nvd diff /run/current-system result | sed "s/^/\t│ /"
    echo "press any key to continue "
    read
    echo -e "\t└──${NC}DONE ${BLUE_BOLD}nvd${NC}"
    echo -e "Running ${YELLOW_BOLD}diff${NC}"
    diff --color=always -r /run/current-system result > result.diff
    cat result.diff | sed "s/^/\t│ /"
    echo -e "\t└──${NC}DONE ${BLUE_BOLD}diff${NC} @ ${pwd}/result.diff"
}

function run-remote-deploy() {
    : Builds locally the system and deploys to an external system
    :  Usage: skyg remote-deploy {target} {cmd}
    target=${1}
    cmd=${2}
    $ROOT_FOLDER/bin/extra/build-remote-nixos ${target} ${cmd}
}


function run-build-all() {
    : Builds all remote and local configurations
    :  Usage: skyg build-all
    mkdir -p results
    
    nix flake show --json | jq -r -c '.nixosConfigurations | keys[]' | while read i; do
        echo "[[SKYG]] Building current $i"
        sudo nixos-rebuild build --flake .#$i
        rm -f results/$i-result
        mv result results/$i-result
    done
    
    nix flake update
    
    rm -f diffs
    mkdir diffs
    nix flake show --json | jq -r -c '.nixosConfigurations | keys[]' | while read i; do
        echo "[[SKYG]] Building new $i"
        sudo nixos-rebuild build --flake .#$i
        rm -f results/$i-result-post
        mv result results/$i-result-post
        nvd diff results/$i-result results/$i-result-post > diffs/$i
    done
    
}


function list_run_functions() {
    declare -F | awk '$3 ~ /^run-/{sub("run-", "", $3); print $3}'
}

all_functions=$(list_run_functions)

for f in ${all_functions[@]}; do
    if [ "$1" == "$f" ]; then
        echo -e "Running ${BLUE_BOLD}$1${NC}"
        run-$1 ${@:2}
        ecode=$(echo $?)
        echo -e "\t└──${NC}DONE ${BLUE_BOLD}$1${NC}"
        exit $ecode
    fi
done

echo -e "Invalid Command '$1' please select one of${NC}"

for function_name in $all_functions; do
    start_line=$(grep -n -m 1 "function run-$function_name" "${BASH_SOURCE[0]}" | cut -d: -f1)
    end_line=$(awk "NR > $start_line && /^}/ {print NR; exit}" "${BASH_SOURCE[0]}")
    function_body=$(sed -n "${start_line},${end_line}p" "${BASH_SOURCE[0]}")
    description=$(echo "$function_body" | sed -n '/^\s*:/,/^\s*[^:]/p' | sed 's/^\s*:\s*/ │ /')
    echo -e "$BOLD\r$MENAME \`${function_name}\`$NC\n${description}\n └──────────\n"
done
