#!/bin/dash
#jamesbond 2012, 2017, 2019, 2022
#JakeSFR 2022

### localisation
export TEXTDOMAIN=get_app
. gettext.sh

### config
APPTITLE="$(gettext 'VirtualBox Installer')"
TMPDIR="${TMPDIR:-/tmp}"
WORKDIR="${TMPDIR}/VBOX"

### helpers
die() {
	splash	# clean previous dialog, if any
	if [ "$DISPLAY" ]; then
		Xdialog --title "$APPTITLE" --infobox "$@" 0 0 10000
	else
		echo "$@"
	fi
	exit 1
}

# $1-text, returns true/false
yesno() {
	local p
	if [ -z "$DISPLAY" ]; then
		printf "$(gettext '%s\nType [yes] to continue: ')" "$1"
		read p
		case "$p" in
			yes) return 0
		esac
		return 1
	else
		Xdialog --title "$APPTITLE" --yesno "$1" 0 0
	fi
}

# $1-text
splash() {
    if [ -z "$DISPLAY" ]; then
        echo "$1"
    else
        if [ "$1" ]; then
            [ $SPID ] && kill $SPID
            Xdialog --title "$APPTITLE" --no-buttons --infobox "$1" 0 0 100000000 &
            SPID=$!
        else
            [ $SPID ] && kill $SPID
            SPID=""
        fi
    fi
}

# are we root?
check_root() {
	if [ $(id -u) -ne 0 ]; then
		die "$(gettext 'You must be root.')"
	fi
}

have_devx() {
	if ! which make > /dev/null || ! which gcc > /dev/null; then
		die "$(gettext 'Please load devx SFS first.')"
	fi
}

have_kernel_source() {
	if ! [ -d /usr/src/linux-$(uname -r) ]; then
		die "$(gettext 'Please load kernel source SFS first.')"
	fi
}

# $1-pkgname (no space)
download_support_libraries() {
	local PKG=$1
	if ! slapt-get --installed | grep -q "^$PKG.*$ARCH"; then
		splash "$(gettext "Updating package list, please wait...")"
		slapt-get --update --no-prompt
		splash "$(gettext "Installing $PKG, please wait...")"
		if ! slapt-get --install --no-prompt $PKG; then
			die "$(gettext "Failed to install $PKG.")"
		fi
	fi
}

### main
# 0. Confirmation
! yesno "\
$(gettext 'This will download and install VirtualBox from their official website.')
$(gettext 'If you already have an existing installation, it will be updated.')
$(gettext 'You need to be root and have devx and kernel-source SFS already loaded.')

$(gettext 'Are you sure you want to continue?')
" && exit

# 1. sanity checks
check_root
have_devx
have_kernel_source

# 2. which version to install?
RESULT=$(Xdialog --title "$APPTITLE" \
		--stdout \
		--no-tags \
		--radiolist "$(gettext 'Which version to install?')" 10 50 3 \
		"LATEST-STABLE.TXT" "$(gettext 'Latest stable')" on "LATEST.TXT" "$(gettext 'Latest mainline')" off)
[ $? -ne 0 ] && die "$(gettext 'Cancelled...')"

# 3. check version
VERSION=$(wget -qO - http://dlc.sun.com/virtualbox/$RESULT)
[ -z "$VERSION" ] && die "$(gettext 'Cannot find latest VirtualBox version.')"

# 4. check installed version
if [ -e /etc/vbox/vbox.cfg ]; then
	. /etc/vbox/vbox.cfg # get INSTALL_VER
	[ "$INSTALL_VER" = "$VERSION" ] && die "$(eval_gettext 'You already have the latest version: $VERSION')"
fi

# 5. install support library (for VBox >= 7)
if [ ${VERSION%%.*} -ge 7 ]; then
	download_support_libraries krb5
fi

# 6. Download
splash "$(eval_gettext 'Downloading Virtual Box version $VERSION, please wait ...')"

mkdir -p "$WORKDIR"; cd "$WORKDIR"
rm -f "${WORKDIR}/"*	# remove previous downloads, if any
TMPFILE=$(mktemp)
wget -O $TMPFILE http://dlc.sun.com/virtualbox/$VERSION/
FILE=$(sed -n '/amd64\.run/ {s/^.*"\(V.*_amd64.run\)".*$/\1/;p}' $TMPFILE)
rm $TMPFILE
wget http://dlc.sun.com/virtualbox/$VERSION/$FILE || die "$(gettext 'Failed to download Virtual Box Installer.')"

# 7. remove busybox version, vbox since 5.x doesn't work with that
#rm -f /bin/readlink # newer Fatdog's have a workaround for this, not needed anymore

# 8. Check for sb-state, we will have to patch it (version 6.1.40 and 7.0.0 onwards)
if type mokutil > /dev/null; then
	case "$(mokutil --sb-state)" in
		*"SecureBoot enabled"*) PATCH_VBOXDRV=1 ;;
	esac
fi

# 9. Install it
splash "$(eval_gettext 'Installing Virtual Box version $VERSION, please wait ...')"
if ! sh $FILE; then
	# always fail in sb because VB does not support us, so disable sb setup and try again.
	if [ -e /etc/init.d/vboxdrv ] && [ "$PATCH_VBOXDRV" ]; then
		sed -i -e 's/mokutil/mockutil/' /etc/init.d/vboxdrv
		/etc/init.d/vboxdrv setup ||
		die "$(gettext 'Failed to install Virtual Box.')"
	else
		die "$(gettext 'Failed to install Virtual Box.')"
	fi
fi

splash

# 10. Optional Extension Pack
if yesno "$(gettext 'Do you also want to download and install Extension Pack?')"; then
	splash "$(gettext 'Downloading Extension Pack, please wait ...')"
	EXTPACK="Oracle_VM_VirtualBox_Extension_Pack-${VERSION}.vbox-extpack"
	wget http://dlc.sun.com/virtualbox/$VERSION/$EXTPACK || die "$(gettext 'Failed to download Extension Pack.')"
	splash "$(gettext 'Installing Extension Pack, please wait ...')"
	rm -rf /opt/VirtualBox/ExtensionPacks/Oracle_VM_VirtualBox_Extension_Pack	# the only way to install new one is to delete the current one
	yes | VBoxManage extpack install --replace "${WORKDIR}/$EXTPACK" || die "$(gettext 'Failed to install Extension Pack.')"
fi

# 11. Done.
splash
Xdialog --infobox "$(eval_gettext 'Done. The original files are stored in $WORKDIR in case you want to keep them.')" 0 0 10000
