#!/bin/bash

# SafeSurfer-Desktop - sscli

#
# Copyright (C) 2018 Caleb Woodbine <info@safesurfer.co.nz>
#
# This program 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.
#
# This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
#

sscliDir="$(dirname $(realpath $0))"
arg="$1"
resolvconf="/etc/resolv.conf"
primaryDNS="104.197.28.121"
secondaryDNS="104.155.237.225"
appVersion="1.0.1"
appBuild="13"

function sudoUserCheck() {
# check if user is root
if [ ! "$(whoami)" = "root" ]
then
	echo "ERROR: You must be root to use some this program."
	exit 1
fi
return 0
}

function printHelpMenu() {
# print the help menu
cat << EOF
The Safe Surfer command line utility

Usage: sscli [option]

Options:
	disable  disable the DNS
	enable   enable the DNS
	flush	 flush the DNS cache
	launch   launch the desktop app
	service  check and enable as service
	status	 get the status of the service
	help     print this menu
EOF
}

function enableBackgroundService() {
# a process which checks if services isn't enabled, then enables it.
while true
do
	if ! checkServiceState
	then
		echo "SERVICE: Not enabled... setting up."
		setDNSservers
	else
		echo "SERVICE: User is already protected."
	fi
sleep 10m
done
}

function checkServiceState() {
# return if the service is enabled
[ ! -z "$VERBOSE" ] && echo "STATUS: Checking status of service"
if eval "$fetchCmd" | grep -q '<meta name="ss_status" content="protected">' || grep -E -q "$primaryDNS|$secondaryDNS" /etc/resolv.conf
then
	return 0
else
	return 1
fi
}

function flushAndRestart() {
# flush and restart DNS related services
local success
success=false
if systemctl is-active --quiet nscd
then
	service nscd reload && service nscd restart && echo "* Flushed nscd DNS cache and restarted"
	success=true
fi

if [ -x $(which systemd-resolve 2> /dev/null) ] && [ ! -z $(which systemd-resolve 2> /dev/null) ]
then
	systemd-resolve --flush-caches && echo "* Flushed systemd-resolve DNS cache"
	success=true
fi

if [ "$success" = false ]
then
	echo "ERROR: cannot find nscd or systemd-resolve; failed to flush DNS cache"
	exit 1
fi
}

function setDNSservers() {
# set DNS settings
mv "$resolvconf"{,.before_safesurfer}
echo -e "#GENERATED BY Safe Surfer desktop (sscli), backed up to '/etc/resolv.conf.before_safesurfer'\\nnameserver $primaryDNS\\nnameserver $secondaryDNS" > "$resolvconf"

if checkServiceState
then
	echo "DNS settings installed successfully."
	chattr +i /etc/resolv.conf
	flushAndRestart
	return 0
else
	echo "ERROR: DNS settings failed to install; Reverting changes."
	mv "$resolvconf"{.before_safesurfer,}
	return 1
fi
}

function restoreDNSservers() {
# restore DNS settings
chattr -i /etc/resolv.conf
if [ ! -e "$resolvconf.before_safesurfer" ]
then
	echo "ERROR: Unable to find backup."
	exit 1
fi
mv "$resolvconf"{.before_safesurfer,}
if ! checkServiceState
then
	echo "DNS settings removed successfully."
	flushAndRestart
	return 0
else
	echo "ERROR: DNS settings failed to remove."
	return 1
fi
}

cat << EOF
---------------
- sscli       -
- by          -
- Safe Surfer -
---------------

EOF

if [ ! -z "$(which curl 2> /dev/null)" ]
then
	fetchCmd="curl -s check.safesurfer.co.nz"

elif [ ! -z "$(which wget 2> /dev/null)" ]
then
	fetchCmd="wget -qO- check.safesurfer.co.nz"

else
	echo "ERROR: Cannot find 'curl' or 'wget'."
	exit 1
fi

case "$arg" in
	enable|-e|--enable)
		shift
		sudoUserCheck
		if [ ! "$1" = "-f" ] && [ ! "$1" = "force" ]
		then
			VERBOSE=0 checkServiceState && echo "SERVICE: Already enabled." || setDNSservers
		else
			setDNSservers
		fi
		;;

	disable|-d|--disable)
		shift
		sudoUserCheck
		if [ ! "$1" = "-f" ] && [ ! "$1" = "force" ]
		then
			VERBOSE=0 checkServiceState && restoreDNSservers || echo "SERVICE: Already disabled."
		else
			restoreDNSservers
		fi
		;;

	service|-s|--service)
		sudoUserCheck
		enableBackgroundService
		;;

	check|status|-c|--check|-s|--status)
		VERBOSE=0 checkServiceState && echo "SERVICE: Enabled." || echo "SERIVCE: Disabled."
		;;

	launch|-l|--launch)
		[[ "$(whoami)" = "root" ]] && echo "ERROR: You can't launch the desktop app as root." && exit 1
		echo "Launching desktop app..."
		if [ -z "$ISAPPIMAGE" ]
		then
			"${sscliDir}/../lib64/SafeSurfer-Desktop/safesurfer-desktop"
		else
			exec "${APPRUN}"
		fi
		;;

	flush|-f|--flush)
		sudoUserCheck
		flushAndRestart
		;;

	-v|--version)
		echo -e "\\nVersion: $appVersion\\nBuild: $appBuild"
		;;

	*)
		printHelpMenu
		;;
esac