#!/bin/dash
#jamesbond 2012, 2017

### config
APPTITLE="VirtualBox Installer"
TMPDIR=${TMPDIR:-/tmp}

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

### main
# 1. sanity checks
if ! which make > /dev/null || ! which gcc > /dev/null; then
	die "Load devx first."
fi

if ! [ -d /usr/src/linux-$(uname -r) ]; then
	die "Load kernel source first."
fi


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

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

# 4. Download
Xdialog --no-buttons --infobox "Downloading version $VERSION, please wait ..." 0 0 1000000 &
PID=$!

mkdir -p $TMPDIR; cd $TMPDIR
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
kill $PID

# 5. remove busybox version, vbox since 5.x doesn't work with that
rm -f /bin/readlink

# 6. Install it
Xdialog --no-buttons --infobox "Installing version $VERSION, please wait ..." 0 0 1000000 &
PID=$!
sh $FILE
kill $PID

# 7. Done.
Xdialog --infobox "Done. The original file is stored in $TMPDIR/$FILE in case you want to keep it." 0 0 10000

