#!/bin/bash

function write_action_to_log()
{
	local scriptname=`basename $0`
	uid=$SUDO_USER
	if [ -n "$USER" ] && [ "$USER" != "root" ]; then
		exit 1
	fi
	if [ -z "$2" ]; then
		result="success"
	elif [ "$2" = "failed" ]; then
		result="failed"
	else
		uid="$2"
		result="success"
	fi
	if [ "$1" = "disable" ] || [ "$1" = "enable" ] || [[ "$1" =~ ^set[0-2]$ ]]; then
		type=$1
	else
		type="error"
	fi
	echo "`date +%Y.%m.%d-%T` uid=$uid name=astra-safepolicy version=$(dpkg -s astra-safepolicy | grep -m 1 "Version:" | cut -d' ' -f2) script=$scriptname type=$type res=$result" >> /var/log/astra-safepolicy.log
}
TEXTDOMAINDIR=/usr/share/locale
TEXTDOMAIN=astra-safepolicy

mode=$1

if [ "$UID" != "0" ]; then
    echo $"You must be root to run this script"
    exit 1
fi

if [ -z `which ufw` ]; then
	if [ "$mode" = "status" ]; then echo $"INACTIVE"; fi
	echo $"UFW not found"
	write_action_to_log "$mode" "failed"
	exit 1
fi

workaround()
{
	mkdir ~/.ufw-tmp
	label=`/usr/sbin/pdpl-file /etc/ufw/ufw.conf 2> /dev/null`
	if ! [ -z $label ]; then
		/usr/sbin/pdpl-file $label ~/.ufw-tmp
	fi
	export TMPDIR=~/.ufw-tmp
}

workaround_cleanup()
{
	rm -rf ~/.ufw-tmp
}

if [ "$mode" = "enable" ]; then
	firewalld=`systemctl is-enabled firewalld 2> /dev/null`
	if [ "$firewalld" = "enabled" ]; then
		echo $"firewalld is already enabled, disable it before enabling ufw"
		write_action_to_log "$mode" "failed"
		exit 1
	fi
	workaround
	ufw enable
	workaround_cleanup
	
	write_action_to_log "enable"	

elif [ "$mode" = "disable" ]; then 
	workaround
	ufw disable
	workaround_cleanup
	
	write_action_to_log "disable"	

elif [ "$mode" = "status" ] || [ "$mode" = "is-enabled" ]; then
	if [ "`LANG=C ufw status | head -n1`" = "Status: active" ]; then
		if [ "$mode" = "status" ]; then echo $"ACTIVE"; else echo $"ENABLED"; fi
		exit 0;
	else
		if [ "$mode" = "status" ]; then echo $"INACTIVE"; else echo $"DISABLED"; fi
		exit 1;
	fi

else
	echo $"Usage: $0 <enable/disable/status/is-enabled>"
	write_action_to_log "$mode" "failed"
	exit 1
fi
exit 0
