#!/bin/env fish
begin
    set -l varName WIN11_IMAGE_PATH
    set -l $varName
    set -l dir (status dirname)
    source "$dir/lib/choose-disk.fish"
    source "$dir/lib/confirm.fish"
    set $varName (bash -c ". $(string escape $dir)/.env; echo \$$varName" 2> /dev/null)

    [ ! -z "$$varName" ]
    or begin
        if [ ! -f "$dir/.env" ]
            cp $dir/.env.template $dir/.env
        end

        echo "Please epecify the path to the Windows 11 ISO image in your .env file located at:"
        realpath --relative-to (pwd) (realpath $dir/.env)
        exit 1
    end

    function mkWinPath
        sed "s/\//\\\\/g"
    end

    argparse --name (status filename) -x "iso,usb" iso usb debug -- $argv
    or exit 1

    set -l mountDir /mnt
    set -l setupLabel winiso-valhalla
    set -l projectPath PortValhalla
    set -l systemDrivePath "sources/\$OEM\$/\$1"
    set -l pwshPath pwsh
    set -l localProjectPath "$systemDrivePath/$projectPath"
    set -l cacheDir ~/.cache/winiso-valhalla
    set -l winpe "$cacheDir/winpe.iso"
    set -l winPath "$mountDir/win"
    set -l winpePath "$mountDir/winpe"
    set -l valhallaPath "$mountDir/winiso-valhalla"
    set -l winpeOverlay (mktemp -d)
    set -l winOverlay (mktemp -d)
    set -l upperDir (mktemp -d)
    set -l workDir (mktemp -d)
    set -l editionField "Edition ID"
    set -l wimFile "sources/install.wim"

    set -l tempPaths \
        "$winpeOverlay" \
        "$winOverlay" \
        "$upperDir" \
        "$workDir"

    set -l mountPaths \
        "$valhallaPath" \
        "$winPath" \
        "$winpePath"

    set -l files

    set -l fileDefinitions (
            # Intel LAN driver
        ) \
        drivers/network/intel \
        "https://dlcdnets.asus.com/pub/ASUS/mb/04LAN/DRV_LAN_Intel_I211_UWD_TP_W10_64_VER12151841_20190306R.zip?model=ROG%20ZENITH%20EXTREME%20ALPHA" \
        zip \
        . (
            # Marvell LAN driver
        ) \
        drivers/network/marvell \
        "https://dlcdnets.asus.com/pub/ASUS/mb/04LAN/DRV_LAN_Marvell_TP_TSD_W11_64_V3130_20211118R.zip?model=ROG%20ZENITH%20EXTREME%20ALPHA" \
        zip \
        ./x64 (
            # Git
        ) \
        software/git \
        "https://github.com/git-for-windows/git/releases/download/v2.41.0.windows.1/PortableGit-2.41.0-64-bit.7z.exe" \
        exe \
        . (
            # PowerShell Core
        ) \
        software/pwsh \
        "https://github.com/PowerShell/PowerShell/releases/download/v7.3.7/PowerShell-7.3.7-win-x64.zip" \
        zip \
        .

    for i in (seq 1 4 (count $fileDefinitions))
        set -l entry $fileDefinitions[$i.."$(math "$i" + 3)"]
        set -l name "$entry[1]"
        set -l url "$entry[2]"
        set -l type "$entry[3]"
        set -l dir "$entry[4]"
        set -l winPath "X:\\$(echo "$name" | mkWinPath)"
        set -l file "$cacheDir/$name.$type"
        set -l target "$winpeOverlay/$name"

        set -a files \
            "$file" \
            "$dir" \
            "$name" \
            "$target" \
            "$winPath"

        and mkdir -p (dirname "$file")

        and if [ ! -f "$file" ]
            curl -L "$url" -o "$file"
        end

        and begin
            set -l tempDir (mktemp -d)

            and switch $type
                case zip
                    unzip "$file" -d "$tempDir"
                case exe
                    pushd "$tempDir" >/dev/null
                    and 7z x "$file"
                    and popd >/dev/null
            end

            and mkdir -p (dirname "$target")
            and cp -r "$tempDir/$dir" "$target"
            and rm -rf "$tempDir"
        end
    end

    set -l intel $files[1..5]
    set -l marvell $files[6..10]
    set -l git $files[11..15]
    set -l pwsh $files[16..20]

    and cp -r "$dir/winpefs"/* "$winpeOverlay"

    and begin
        set -l startupFile "$winpeOverlay/Windows/System32/startnet.cmd"
        and mkdir -p (dirname "$startupFile")

        begin
            set -l path

            and for sw in git pwsh
                set -a path $$sw[1][5]
            end

            and printf %s\n \
                "@echo off" (
                    string join ";" \
                        "set PATH=%PATH%" \
                        $path \
                        "$git[5]\\bin"
                ) \
                "set SETUP_LABEL=$setupLabel" \
                (
                    begin
                        if [ -n  "$_flag_debug" ]
                            echo "set DEBUG=1"
                        end
                    end
                ) \
                "set PWSH_PATH=$(echo "$pwshPath" | mkWinPath)" \
                "set LOCAL_PROJECT_PATH=$(echo "$localProjectPath" | mkWinPath)" \
                "set REMOTE_PROJECT_PATH=$(echo "$projectPath" | mkWinPath)" \
                "echo Loading Drivers..." \
                'pwsh -file "X:\Scripts\Drivers.ps1"' \
                "echo Configuring Network..." \
                wpeinit \
                "echo Configuring keyboard layout..." \
                "wpeutil SetKeyboardLayout 0807:00000807" \
                "echo Disabling Energy Saving Mode..." \
                "powercfg /s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c" \
                'start pwsh -NoExit -ExecutionPolicy bypass -file "X:\Scripts\Startup.ps1"'
        end | sudo tee "$startupFile" >/dev/null
    end

    and mkdir -p "$(dirname "$winpe")"
    and sudo mount --mkdir $$varName "$winPath"
    and mkwinpeimg --iso --arch amd64 --overlay "$winpeOverlay" --windows-dir "$winPath" "$winpe"
    and sudo mount --mkdir "$winpe" "$winpePath"

    and begin
        echo "$wimFile"
    end | rsync --files-from=/dev/stdin "$winPath" "$winOverlay"

    and begin
        set -l wimFile "$winOverlay/$wimFile"
        and chmod u+w (dirname "$wimFile")
        and chmod u+w "$wimFile"

        and while [ ! (wiminfo "$wimFile" 1 | grep "^$editionField" | cut -d ":" -f2 | string trim) = Professional ]
            wimdelete --soft "$wimFile" 1
        end

        and while wiminfo "$wimFile" 2 &>/dev/null
            wimdelete --soft "$wimFile" 2
        end

        and wimoptimize "$wimFile" || true
        and chmod u-w "$wimFile"
        and chmod u-w (dirname "$wimFile")
    end

    begin
        set -l projectPath "$winOverlay/$localProjectPath"
        set -l rootDir "$projectPath"

        and while [ ! -d "$rootDir" ]
            set rootDir (dirname "$rootDir")
        end

        and chmod u+w "$rootDir"
        and mkdir -p "$projectPath"
        and cp -r "$pwsh[4]" "$winOverlay/$systemDrivePath/$pwshPath"
        and fish "$dir/../scripts/lib/copy-repo.fish" "$projectPath"
        and rm -rf "$projectPath/archiso"

        and begin
            source "$dir/../scripts/lib/settings.fish"

            and for name in (getProfiles | jq '.[]' --raw-output0 | string split0)
                set -l CONFIG_NAME "$name"
                set -l file "$projectPath/.config/$name.json"
                and mkdir -p (dirname $file)
                and getConfig "valhalla.windows.config" --json >"$file"
            end
        end

        and chmod -R u-w "$rootDir"
    end

    and sudo mount --mkdir -t overlay overlay -o lowerdir="$winOverlay":"$winpePath":"$winPath",upperdir="$upperDir",workdir="$workDir" "$valhallaPath"

    and if [ -z "$_flag_usb" ]
        set -l isoFile "$(status dirname)/build/winiso-valhalla.iso"
        and mkdir -p (dirname "$isoFile")

        and mkisofs \
            -V "$setupLabel" \
            -no-emul-boot \
            -b "efi/microsoft/boot/efisys.bin" \
            -iso-level 4 \
            -udf \
            -joliet \
            -disable-deep-relocation \
            -omit-version-number \
            -relaxed-filenames \
            -output "$isoFile" \
            "$valhallaPath"
    else
        set -l bootPath "$mountDir/boot"
        set -l dataPath "$mountDir/data"

        set -a mountPaths \
            "$bootPath" \
            "$dataPath"

        chooseDisk winDisk
        and echo "Proceeding will cause the disk `$winDisk` to be wiped."

        and if ! confirm "Are you sure you want to continue?" n
            exit 1
        end

        and sudo shred -vfzn 0 -s 512 "$winDisk"

        and begin
            printf %s\n \
                "label: dos" \
                "size=+2G type=uefi" \
                "type=07"
        end | sudo sfdisk "$winDisk"

        and sudo partprobe
        and sudo udevadm trigger

        and begin
            set -l disks
            set -l diskPath (find -L /dev/disk/by-diskseq -samefile $winDisk)
            set -l bootDisk "$diskPath-part1"
            set -l dataDisk "$diskPath-part2"
            and sudo mkfs.fat -F 32 -n BOOT "$bootDisk"
            and sudo mkfs.ntfs -fFL "$setupLabel" "$dataDisk"
            and sudo mount --mkdir "$bootDisk" "$bootPath"
            and sudo mount --mkdir "$dataDisk" "$dataPath"
            and sudo cp -r "$winpePath"/* "$bootPath"

            and sudo cp -r "$valhallaPath"/* "$dataPath"
            and sudo cp -r "$valhallaPath/efi" "$bootPath"
        end
    end

    for path in $mountPaths
        sudo umount -vf "$path"
    end

    for path in $mountPaths $tempPaths
        sudo rm -rf "$path"
    end
end