#!/bin/env fish
set -l dir (status dirname)
source "$dir/../../lib/action.fish"

function backupAction -V dir
    source "$dir/../../lib/hooks.fish"

    if not type -q getDeploymentScript
        function getDeploymentScript
            echo "No deployment script specified! No software will be installed." 1>&2
            false
        end
    end

    set -l deployScript (getDeploymentScript)

    if [ -z "$VALHALLA_BACKUP_DIR" ]
        if fish "$dir/../../../lib/modules/partition/confirm.fish" "Do you wish to store the backup on an SSH server?" n
            read -xP "Please specify the host name of the SSH server: " VALHALLA_BACKUP_SERVER
            read -xP "Please specify the port of the SSH server (default 22): " VALHALLA_BACKUP_SERVER_PORT
            read -xP "Please specify the name of the user to log in to the SSH server: " VALHALLA_BACKUP_SERVER_USER
            read -xP "Please specify the path to the key file for logging in to the SSH server: " VALHALLA_BACKUP_SERVER_KEY

            if [ -z "$VALHALLA_BACKUP_SERVER_PORT" ]
                set -x VALHALLA_BACKUP_SERVER_PORT 22
            end

            if [ -n "$VALHALLA_BACKUP_SERVER_USER" ]
                set -x VALHALLA_BACKUP_SERVER "$VALHALLA_BACKUP_SERVER_USER@$VALHALLA_BACKUP_SERVER"
            end

            echo
            echo "$(tput setaf 3)==== WARNING ====$(tput sgr0)"
            echo "For a seamless experience, please make sure that you are able to establish an unattended ssh connection using key authentication."
            echo
            echo "$(tput bold)This command should succeed without user interaction:$(tput sgr0)"
            echo "sudo ssh -o PasswordAuthentication=no -i $(string escape -- "$VALHALLA_BACKUP_SERVER_KEY") -p $VALHALLA_BACKUP_SERVER_PORT $VALHALLA_BACKUP_SERVER true"
            read -P "Press enter once you're done: "
            echo
        end

        read -xP "Please specify the path to the directory to save the backup to: " VALHALLA_BACKUP_DIR
    end

    runHook backupSoftware || begin
        echo "Backing up software..."

        and if [ -n "$deployScript" ]
            source $deployScript backup
        end
    end

    runHook backupUsers || begin
        if [ -n "$deployScript" ]
            for name in (getUsers | jq '.[]' --raw-output0 | string split0)
                echo "Backing up user `$name`..."
                and source $deployScript userBackup --user $name
            end
        end
    end
end

runSetupUserAction backupAction