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

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

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

### helpers
die() {
	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
}

# 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
}

### 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. check version
VERSION=$(wget -qO - http://dlc.sun.com/virtualbox/LATEST.TXT)
[ -z "$VERSION" ] && die "$(gettext '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 "$(eval_gettext 'You already have the latest version: $VERSION')"
fi

# 4. Download
Xdialog --no-buttons --infobox "$(eval_gettext '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 # newer Fatdog's have a workaround for this, not needed anymore

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

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

