#!/bin/bash
# Elevate script
if [ ! "$UID" -eq 0 ]
then
    sudo bash "$BASH_SOURCE"
else
    # Create context directory
    workingDirectory=$(pwd)
    contextRoot=$(mktemp -d)
    cd $contextRoot

    # Initialize variables
    esp=/boot/efi
    defaultBootDir=$esp/EFI/BOOT
    microsoftBootDir=$esp/EFI/Microsoft/Boot

    systemdDirName=/EFI/systemd
    systemdFullName=$esp$systemdDirName
    systemdFile=$systemdFullName/systemd-bootx64.efi

    loaderBaseName=loader.efi
    systemdLoaderFile=$systemdFullName/$loaderBaseName

    # Install PreLoader
    wget https://blog.hansenpartnership.com/wp-uploads/2013/HashTool.efi
    wget https://blog.hansenpartnership.com/wp-uploads/2013/PreLoader.efi

    cp {HashTool,PreLoader}.efi $systemdFullName
    cp $systemdFile $systemdLoaderFile
    efibootmgr --unicode --disk /dev/nvme0n1 --part 0 --create --label "PreLoader" --loader $systemdDirName/PreLoader.efi

    # Add fallbacks
    cp ./HashTool.efi $defaultBootDir
    cp $systemdFile $defaultBootDir/$loaderBaseName
    cp ./PreLoader.efi $defaultBootDir/BOOTx64.EFI

    # Add Microsoft fallbacks
    mkdir -p $microsoftBootDir
    cp ./PreLoader.efi $microsoftBootDir/bootmgfw.efi
    cp ./HashTool.efi $microsoftBootDir
    cp $systemdFile $microsoftBootDir/$loaderBaseName

    # Remove context directory
    cd $workingDirectory
    rm -rf $contextRoot
fi