#!/bin/sh

umask 022

profile_dir=/usr/share/crypto-policies
base_dir=/etc/crypto-policies
local_dir="$base_dir/local.d"
backend_config_dir="$base_dir/back-ends"
state_dir="$base_dir/state"
errcode=0
nocheck=0
profile=''

if test $# -ge 1;then
	case "$1" in
		--set)
			profile="$2"
			;;
		--no-check)
			nocheck=1
			;;
		--show)
			cat $base_dir/config|grep -v "^#"|sed '/^$/d'
			exit 0
			;;
		--is-applied)
			time1=$(stat -c %Y $state_dir/current)
			time2=$(stat -c %Y $base_dir/config)
			if test -z "$time1" || test -z "$time2";then
				exit 77
			fi
			if test $time1 -ge $time2;then
				echo "The configured policy is applied"
				exit 0
			else
				echo "The configured policy is NOT applied"
				exit 1
			fi
			;;
		*)
			echo "usage: $0 --set [POLICY]"
			echo "usage: $0 --show"
			echo "usage: $0 --no-check"
			echo "usage: $0 --is-applied"
			echo "usage: $0"
			exit 0
			;;
	esac
fi

mkdir -p $backend_config_dir >/dev/null 2>&1
mkdir -p $state_dir >/dev/null 2>&1

set_config=0
if test -z "$profile";then
	profile=$(cat $base_dir/config|grep -v ^#)
else
	set_config=1
fi

# remove any legacy profile options
profile=$(echo -n $profile|sed -e 's/@F..//')

if test -z "$profile";then
	#try the OS-installed profile
	profile=$(cat /usr/share/crypto-policies/default-config|grep -v ^#)
	if test -z "$profile";then
		echo "Couldn't read current profile"
		exit 1
	fi
fi

if ! test -d "$profile_dir/$profile";then
	echo "Unknown profile: $profile"
	exit 1
fi

echo "Setting system policy to $profile"
for i in "$profile_dir/$profile/"*;do
	basefile=$(basename "$i")
	file=$(echo -n "$basefile"|sed 's/\.txt/\.config/')
	basefile=$(echo -n "$basefile"|sed 's/\.txt//')

	if test -z $(ls $local_dir/$basefile*.config 2>/dev/null);then
		ln -sf $i "$backend_config_dir/$file"
		if test $? != 0;then
			echo "Failed updating policies, are you root?"
			exit 1
		fi
	else
		rm -f "$backend_config_dir/$file"
		cat $i > "$backend_config_dir/$file"
		if test $? != 0;then
			echo "Failed updating policies, are you root?"
			exit 1
		fi

		cat $local_dir/$basefile-*.config >> "$backend_config_dir/$file"
	fi
done

echo $profile > $state_dir/current

if test $set_config = 1;then
	echo $profile > $base_dir/config
fi

. $profile_dir/reload-cmds.sh

# Old versions seemed to install that file. We no longer use it
rm -f $base_dir/current

exit $errcode
