#!/bin/sh

# This scripts helps the user to automate the GNUnet setup for user services.

if [ $(id -u) -ne 0 ]; then
	echo "Please run this script as root."
	echo "Usage: "`basename $0`" -u USER"
	exit
fi
if [ $# = 0 ]; then
	echo "Usage: "`basename $0`" -u USER"
	exit
fi

while getopts ':u:' OPTION ; do
	case "$OPTION" in
		u) USER="$OPTARG";;
		*) echo "Unknown parameter"; exit;;
	esac
done

CONFIG_PATH="/home/$USER/.config/gnunet.conf"
DOASUSER="chpst -u $USER env HOME=/home/$USER"

echo "Adding user to group gnunet"
adduser $USER gnunet 2>/dev/null

echo "Creating user config at $CONFIG_PATH"
cat > $CONFIG_PATH << EOF
[paths]
GNUNET_RUNTIME_DIR = "/run/gnunet/"

[arm]
START_SYSTEM_SERVICES = NO
START_USER_SERVICES = YES
EOF
chown $USER:$USER $CONFIG_PATH

echo "Creating symlink: gnunet-user-services -> gnunet-$USER-services"
ln -s /etc/init.d/gnunet-user-services /etc/init.d/gnunet-$USER-services

echo "Creating/Renewing GNS certificate authority (CA)"
$DOASUSER gnunet-gns-proxy-setup-ca
echo

echo "Use GNU Name System in Firefox/Chromium by default? [y,N]"
read -r yn
case $yn in
y|Y )
	PORT=$((8000+$(id -u $USER)))
	$DOASUSER gnunet-config -c $CONFIG_PATH \
		--rewrite \
		--section=gns-proxy \
		--option=IMMEDIATE_START \
		--value=YES
	$DOASUSER gnunet-config -c $CONFIG_PATH \
		--rewrite \
		--section=gns-proxy \
		--option=OPTIONS \
		--value="-p $PORT"

	# Firefox
	if [ ! -d  /home/$USER/.mozilla/firefox/*.default ];then
		$DOASUSER timeout 3s firefox --headless # dirty: create profile if not existent
	fi
	for ffprofile in /home/$USER/.mozilla/firefox/*.*/; do
		js=$ffprofile/user.js
		if [ -f $js ]; then
			sed -i '/Preferences for using the GNU Name System/d' $js
			sed -i '/network.proxy.socks/d' $js
			sed -i '/network.proxy.socks_port/d' $js
			sed -i '/network.proxy.socks_remote_dns/d' $js
			sed -i '/network.proxy.type/d' $js
		fi
		echo "// Preferences for using the GNU Name System" >> $js
		echo "user_pref(\"network.proxy.socks\", \"localhost\");" >> $js
		echo "user_pref(\"network.proxy.socks_port\", $PORT);" >> $js
		echo "user_pref(\"network.proxy.socks_remote_dns\", true);" >> $js
		echo "user_pref(\"network.proxy.type\", 1);" >> $js
	done

	# Chromium
	PROFILE=/home/$USER/.profile
	if [ -f $PROFILE ]; then
		sed -i '/CHROMIUM_USER_FLAGS/d' $PROFILE
	fi
	echo "export CHROMIUM_USER_FLAGS=--proxy-server=socks5://localhost:$PORT" \
		>> $PROFILE
	;;
* )
        ;;
esac

echo "Done. You may need to log out and log in again to use GNUnet with your user '$USER'."
