#!/bin/env fish
begin
    set -l dir (status dirname)
    source "$dir/../Scripts/config.fish"
    source "$dir/../Scripts/hooks.fish"
    set -l name (getConfig valhalla.setupUser.name)
    set -l mountDir (getConfig valhalla.partition.rootDir)
    set -l projectRoot (realpath "$dir/../../..")
    set -l projectName (basename "$projectRoot")
    set -l PROJECT_CLONE_ROOT "/opt/$(basename "$projectName")"
    set -l script (mktemp)

    function getCloneFile -S -a path
        set -l relativeDir (realpath --relative-to "$projectRoot" "$dir")
        set -l relativePath (realpath --relative-to "$dir" "$path")
        echo "$PROJECT_CLONE_ROOT/$relativeDir/$relativePath"
    end

    getConfig valhalla.partition.script > "$script"
    bash "$script"
    and source "$dir/../../copy-repo.fish" "$mountDir$PROJECT_CLONE_ROOT"
    and runHook setupOS || true
    and runHook autologin || true

    # Copy `nixpkgs` channel
    and begin
        set -l channelDir /nix/var/nix/profiles/per-user/root/channels/nixpkgs
        mkdir -p (dirname "$mountDir/$channelDir")
        cp -r "$channelDir" "$mountDir/$channelDir"
    end

    and begin
        set -l script (string escape (getCloneFile (getInstallerScript)))
        printf %s\n \
            "cd $PROJECT_CLONE_ROOT" \
            "export CONFIG_MODULE=$(string escape (getCloneFile "$CONFIG_MODULE"))" \
            "export INSTALLER_SCRIPT=$script" \
            "$script"
    end | chroot "$mountDir" tee /root/.bash_profile > /dev/null

    and echo "Setup finished!"
    and echo "Please reboot your machine"
end