#!/bin/env fish
begin
    set -l nixVersion nixos-24.05
    set -l projectName archiso-valhalla
    set -l overlayDir (mktemp -d)
    set -l upperDir (mktemp -d)
    set -l workDir (mktemp -d)
    set -l cacheRoot ~/".cache/$projectName"
    set -l nixCache "$cacheRoot/nixpkgs/$nixVersion"
    set -l root airootfs
    set -l rootHome "$overlayDir/$root/root"
    set -l profileDir "/mnt/$projectName"
    set -l projectDir "$rootHome/PortValhalla"
    set -l nixDir "$profileDir/$root/nix/var/nix/profiles/per-user/root/channels/nixpkgs"

    mkdir -p "$rootHome"
    and fish "$(status dirname)/../../scripts/copy-repo.fish" "$projectDir"

    and begin
        if [ ! -d "$nixCache" ]
            mkdir -p "$nixCache"
            and git clone https://github.com/NixOS/nixpkgs.git --depth=1 -b "$nixVersion" "$nixCache"
            and rm -rf "$nixCache/.git"
        end
    end

    and sudo mount --mkdir -t overlay overlay -o lowerdir=.:"$overlayDir",upperdir="$upperDir",workdir="$workDir" "$profileDir"
    and sudo mount --mkdir --bind "$nixCache" "$nixDir"
    and sudo mkarchiso $argv "$profileDir"
    sudo umount "$nixDir"
    and sudo umount "$profileDir"
end