#!/bin/sh


PKG_CONF_FILE=package.conf

WHITELIST_FILE=/usr/share/acap_whitelist/whitelist.sha
CHECKSUM_CMD=sha256sum

__root_prohibited() {
	local _prop_val

	_prop_val=$(parhandclient --nocgi --nolog get properties.System.AxisLimitedAccess - RAW 2>&1 || :)
	[ "$_prop_val" = yes ]
}

__pkgconf_value() {
	local _value=
	local IFS='
'
	for _line in $(tar -Oxf $1 $PKG_CONF_FILE); do
		if [ ${_line%%=*} = "$2" ]; then
			_value=${_line#*=}
			break
		 fi
	done
	eval "$3=$_value"
}

__run_as_root() {
	local _user= _group=

	[ $# -eq 1 ] && [ "$1" ] || {
		error "No eap file. Assuming root."
		return 0
	}
	__pkgconf_value $1 APPUSR _user
	__pkgconf_value $1 APPGRP _group
	[ "$_user" = root ] || [ "$_group" = root ]
}

__is_whitelisted() {
	local _eap_path _line _result=rejected

	[ $# -eq 1 ] && [ "$1" ] || {
		error "No eap file path. Assuming root."
		return 0
	}
	_eap_path=$1

	command -v $CHECKSUM_CMD >/dev/null 2>&1 || {
		warning "Whitelist verification failed: $CHECKSUM_CMD missing."
		return 1
	}
	[ -f "$_eap_path" ] || {
		warning "Whitelist verification failed: Package file not found."
		return 1
	}
	[ -f $WHITELIST_FILE ] || {
		information "Whitelist verification passed: No whitelist file."
		return 0
	}

	_checksum=$($CHECKSUM_CMD "$_eap_path" || :)
	_checksum=${_checksum%%[[:blank:]]*}
	while read _line; do
		set -- $_line
		if [ "$1" = "$_checksum" ]; then
			_result=passed
			break
		fi
	done <$WHITELIST_FILE

	information "Whitelist verification: $_result"
	[ $_result = passed ]
}