#!/bin/sh
#
# Set default Chromium homepage based on URL fetched from
# command line or LDAP.

set -e

etcfile=/etc/chromium/policies/managed/debian-edu-homepage-ldap.json

if [ ldap:homepage = "$1" ] ; then
    # Allow lookup script to be replaced using /etc/debian-edu/config
    GETDEFAULTHOMEPAGE=/usr/share/debian-edu-config/tools/get-default-homepage
    if [ -e /etc/debian-edu/config ] ; then
	. /etc/debian-edu/config
    fi
    url="$($GETDEFAULTHOMEPAGE || true)"
    if [ -z "$url" ] ; then # No LDAP available On main-server during installation
        url="https://www/"
    fi
else
    url="$1"
fi

if [ -z "$url" ] || [ "about:blank" = "$url" ]; then
    rm $etcfile
else
    cat > $etcfile.new <<EOF
{
  "ShowHomeButton" : true,
  "HomepageLocation" : "$url",
  "HomepageIsNewTabPage" : false,
  "RestoreOnStartup" : 4,
  "RestoreOnStartupURLs" : ["$url"]
}
EOF
    chmod 644 $etcfile.new
    if cmp -s $etcfile $etcfile.new ; then
	rm $etcfile.new
    else
	mv $etcfile.new $etcfile
	logger -t update-chromium-homepage "Updated Chromium default homepage to $url."
    fi
fi
