#!/bin/sh
#
# Start web browser with our welcome web page on first time login, and
# also the first time when a user logs in after the URL to the page has changed.

set -e

# Allow lookup script to be replaced using /etc/debian-edu/config; to make this
# work, add a line GETDEFAULTHOMEPAGE="<URL>" to /etc/debian-edu/config.
GETDEFAULTHOMEPAGE=$(/usr/share/debian-edu-config/tools/get-default-homepage || true)

if [ -e /etc/debian-edu/config ] ; then
	. /etc/debian-edu/config
fi

if [ "$GETDEFAULTHOMEPAGE" ] &&
	echo "$PROFILE" | grep -Eq 'Main-Server|Workstation|Roaming-Workstation|LTSP-Server|Minimal' ; then
	if [ "$GETDEFAULTHOMEPAGE" = "http://www/" ] || [ "$GETDEFAULTHOMEPAGE" = "https://www/" ] ; then
		for lang in $(echo $LANGCODE | tr : " "); do
			if wget -q -O /dev/null ${GETDEFAULTHOMEPAGE}index.html.$lang ; then
				welcomeurl="${GETDEFAULTHOMEPAGE}index.html.$lang"
				break
			else
				welcomeurl=$GETDEFAULTHOMEPAGE || true
			fi
		done
	else
		welcomeurl=$GETDEFAULTHOMEPAGE || true
	fi
else
	welcomeurl=https://blends.debian.org/edu/ || true
fi

if [ -z "$welcomeurl" ] || [ "about:blank" = "$welcomeurl" ]; then
	exit 0
fi

flagdir="$HOME/.debian-edu"
flagfile="$flagdir/welcome-page-shown"

show_welcome_page() {
	mkdir -p "$flagdir"
	echo "$GETDEFAULTHOMEPAGE" > "$flagfile"
	exec x-www-browser "$welcomeurl"
}

if [ ! -f "$flagfile" ] ; then
	show_welcome_page
else
	oldwelcomeurl="$(cat $flagfile)"
	if [ "$GETDEFAULTHOMEPAGE" != "$oldwelcomeurl" ] ; then
		show_welcome_page
	fi
fi
