#!/bin/bash
#
# SPDX-FileCopyrightText: 2022 Saulius Krasuckas <saulius2@ar-fi.lt> | sskras
# SPDX-License-Identifier: BlueOak-1.0.0
# SPDX-FileContributor: Modified 2026-01-16 by Gediminas Mockus <info(at)peropesis.org>
#
# Peropesis live ISO image booting using VirtuaBox VM and VirtualBox command-line interface - VBoxManage.
#

VM_NAME="SuperMachine"
OS_TYPE="Linux_64"
SATA_NAME="SATA"

function print () {
    echo
    echo $*
    echo
}

function colorize () {
    cat - | grep --color -e "^" "$@"
}

print - Retrieving and downloading

#URL containing Peropesis ISO
URL="https://peropesis.org/get-peropesis/"

#Regex pattern for version number
VERSION_REGEX='[0-9]+(\.[0-9]+)+'

#Fetch content and extract version numbers
LATEST_VERSION=$(curl -fsSL "$URL" \
  | grep -oE "$VERSION_REGEX" \
  | sort -V \
  | tail -n 1)

ISO_FILE="Peropesis-${LATEST_VERSION}-live.iso"
ISO_URL="https://peropesis.org/peropesis/${ISO_FILE}"

if [ ! -f $ISO_FILE ]; then
    wget -nv --show-progress -c --content-disposition ${ISO_URL}
else
    echo "$ISO_FILE exist"
fi

print - Creating VM SuperMachine
VBoxManage createvm --name ${VM_NAME} --ostype ${OS_TYPE} --register | colorize -e ${VM_NAME}

print - Listing VMs:
VBoxManage list vms | colorize -e ${VM_NAME}

print - Set VM base memory
VBoxManage modifyvm ${VM_NAME} --cpus 2 --memory 512 --vram 12
VBoxManage showvminfo ${VM_NAME} | grep "Memory size" | colorize -e '[0-9MB]$' -e ''

print - Adding SATA
VBoxManage storagectl ${VM_NAME} --name ${SATA_NAME} --add sata --portcount 2 --bootable on
VBoxManage showvminfo ${VM_NAME} | grep -i storage | colorize -e ${SATA_NAME}

print - Attaching ISO image
VBoxManage storageattach ${VM_NAME} --storagectl ${SATA_NAME} --port 0 --device 0 --type dvddrive --medium ${ISO_FILE}
VBoxManage showvminfo --details ${VM_NAME} | grep "^${SATA_NAME}" | colorize -e ${SATA_NAME} -e "${ISO_FILE}"

print - Starting VM
VBoxManage startvm ${VM_NAME} | colorize -e ${VM_NAME}

print "Press <Enter> to stop and remove VM"
read

print - Powering VM off
VBoxManage controlvm ${VM_NAME} poweroff
until $(VBoxManage showvminfo ${VM_NAME} | grep -q powered.off); do echo -n "."; sleep 1; done; sleep 2

print - Destroying VM
VBoxManage unregistervm ${VM_NAME} --delete

print - Listing VMs
VBoxManage list vms

exit

#
# The end.
#