#!/bin/sh
set -e
cd "$(dirname "$(realpath "$0")")"

alias log='echo [build.sh]'


TMP_DIR="${TMP_DIR:-"$PWD/../tmp"}"
OUT_DIR="${OUT_DIR:-"$PWD/../output"}"
VBOX_VERSION=$(VBoxManage --version | cut -d 'r' -f 1)
VM_NAME="epitls_build"


log "updating environment"
    sudo rm -fr "$TMP_DIR"
    mkdir -p "$TMP_DIR" "$OUT_DIR"
    if ! [ -f "$OUT_DIR/guest_add.iso" ]
    then wget -O "$OUT_DIR/guest_add.iso" "https://download.virtualbox.org/virtualbox/$VBOX_VERSION/VBoxGuestAdditions_$VBOX_VERSION.iso"
    fi


AURS="zerofree"


log "creating package db"
    rm -fr "$TMP_DIR/custom-db"
    mkdir  "$TMP_DIR/custom-db"
    for aur in $AURS
    do
        git clone "https://aur.archlinux.org/$aur.git" "$TMP_DIR/custom-db/$aur"
        ( cd "$TMP_DIR/custom-db/$aur" && makepkg; )
        mv "$TMP_DIR"/custom-db/$aur/$aur-* "$TMP_DIR/custom-db/"
        repo-add "$TMP_DIR/custom-db/custom.db.tar.gz" "$TMP_DIR/custom-db"/$aur-*.pkg.tar.zst
    done


log "creating iso"
    sudo mkarchiso -v -w "$TMP_DIR/wdir" -r -o "$OUT_DIR" "$PWD/profile"
    rm -f                         "$OUT_DIR/install.iso"
    mv "$OUT_DIR"/archlinux-*.iso "$OUT_DIR/install.iso"


if VBoxManage showvminfo $VM_NAME 2> /dev/null
then log "disposing old VM"
    VBoxManage unregistervm $VM_NAME --delete-all
fi


log "creating VM"
    VBoxManage createvm --name=$VM_NAME --ostype=ArchLinux_64 --register
    VBoxManage modifyvm        $VM_NAME --cpus=16 --memory=8192 --vram=32 --firmware=efi
    VBoxManage modifyvm        $VM_NAME --nic1=nat
    VBoxManage createhd --filename="$TMP_DIR/drive.vdi" --size=$((1024 * 20)) --variant=Standard
    VBoxManage storagectl      $VM_NAME       --name=SATA --add sata --bootable on
    VBoxManage storageattach   $VM_NAME --storagectl=SATA --port=0 --device=0 --type=hdd      --medium="$TMP_DIR/drive.vdi"
    VBoxManage storagectl      $VM_NAME       --name=IDE  --add ide
    VBoxManage storageattach   $VM_NAME --storagectl=IDE  --port=0 --device=0 --type=dvddrive --medium="$OUT_DIR/install.iso"
    VBoxManage storageattach   $VM_NAME --storagectl=IDE  --port=1 --device=1 --type=dvddrive --medium="$OUT_DIR/guest_add.iso"


log "running VM with iso"
    virtualboxvm --startvm $VM_NAME --dvd "$OUT_DIR/install.iso"


log "exporting VM"
    VBoxManage modifyvm      $VM_NAME --cpus=4 --memory=4096 --vram=24
    VBoxManage storageattach $VM_NAME --storagectl=IDE  --port=0 --device=0 --medium=none # removes iso after run
    VBoxManage storageattach $VM_NAME --storagectl=IDE  --port=1 --device=1 --medium=none # removes iso after run
    VBoxManage modifyhd "$TMP_DIR/drive.vdi" -compact
    rm -f                               "$OUT_DIR/epitls.ova"
    VBoxManage export $VM_NAME --output="$OUT_DIR/epitls.ova" --vsys=0 --vmname=epitls --description="VM pour le développement à EPITA Toulouse."


log "disposing VM"
    VBoxManage unregistervm $VM_NAME --delete-all
