#!/bin/sh
#
# Updates user's black (white?) lists for Epiphany Adblock.
#
# Author: JM. Philippe <jean-michel.philippe@doudoulinux.org>
#################################
# This file is part of DoudouLinux.
#
# DoudouLinux is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DoudouLinux is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with DoudouLinux.  If not, see <http://www.gnu.org/licenses/>
#################################

# constants
PROGRAM=/usr/lib/epiphany-adblock-lists/get-adblock-lists
DATADIR=/var/lib/epiphany-adblock
USERDIR=$HOME/.gnome2/epiphany/extensions/data/adblock
BLACKLIST=blacklist

# allow the use of an input arg for DATADIR
if [ $# -eq 1 ]; then
	DATADIR=$1
fi
if ! [ -d $DATADIR ]; then
	echo "ERROR: unable to find list directory '$DATADIR'"
	exit
fi

# check we can write to /var/lib to update from the Internet
if [ $(id -un) = "root" ]; then
	echo "*** will now update lists from the Internet"
	$PROGRAM
else
	echo "*** non root user: will not update lists from the Internet."
fi

# check Epiphany directory exists
if ! [ -d $USERDIR ]; then
	mkdir -p $USERDIR
	echo "*** created user directory '$USERDIR'"
fi

# gess langcode
# first try with _, eg. zh_CN
LANGCODE=$(echo $LANG | grep -o '^[^\.@]*')
if ! [ -f $DATADIR/$LANGCODE ]; then
	# now remove _, eg. fr
	LANGCODE=$(echo $LANG | grep -o '^[^\._@]*')
fi

# copy files
if [ -f $DATADIR/$LANGCODE ]; then
	if [ -f $USERDIR/$BLACKLIST ]; then
		mv $USERDIR/$BLACKLIST $USERDIR/$BLACKLIST.old
	fi
	cp $DATADIR/$LANGCODE $USERDIR/$BLACKLIST
	echo "*** successfully updated Epiphany Adblock lists for language '$LANGCODE'"
else
	echo "ERROR: cannot find a list for language '$LANGCODE'"
fi
