#!/bin/sh


PKG_CONF_FILE=package.conf
PKG_PARSER_FILE=/etc/acap/conf/packageparser.conf

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

__root_prohibited() {
	local _prop_val _vapix_val=true

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

	__keyfile_value $PKG_PARSER_FILE Install AllowRoot _vapix_val

	[ "$_prop_val" = yes ] || [ "$_vapix_val" = false ]
}

__keyfile_value() {
	local _group _key _value
	local IFS="="

	[ $# -eq 4 ] || {
		error "Bad number of arguments."
		return 1
	}
	[ -f "$1" ] || {
		error "Missing keyfile $1."
		return 1
	}

	while read -r _key _value; do
		case "$_key" in
		'#'* | ' '* | \t*)
			;
		'['*']')
			_group=$(echo "$_key" | sed 's/^.//; s/.$//')
			;
		*)
			[ -n "$_value" ] || continue

			if [ "$_group" = "$2" ] && [ "$_key" = "$3" ]; then
				information "group $2 with key $3 found in keyfile $1. Value=$_value"
				eval "$4=$_value"
			return 0
			fi
			;
		esac
	done < "$1"

	information "No group $2 with key $3 found in keyfile $1."
	return 1
}

__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"
}

__root_or_deprecated() {
	local _uid

	[ $# -eq 1 ] || {
		error "No user or group provided."
		return 0
	}

	case "$1" in
	"root"| "debugar"| "sudo"| "shadow"| "pwauth"| "wsauth"| "bin"| "adm")
		warning "User or group '$1' deprecated."
		return 0
		;

	*)
		_uid=$(id -u $1); [ $_uid -ne 0 ] || {
			warning "User or group '$1' deprecated."
			return 0
		}
		return 1
		;
	esac
}

__run_as_root() {
	local _user= _group= _allow_root=false

	[ $# -eq 2 ] || {
		error "Bad number of arguments."
		return 1
	}
	[ -f "$1" ] || {
		error "Missing eap file. Assuming root."
		return 0
	}
	__pkgconf_value $1 APPUSR _user
	__pkgconf_value $1 APPGRP _group

	__keyfile_value $PKG_PARSER_FILE Install AllowRoot _allow_root
	[ "$_allow_root" = true ] || {
		eval "$2=yes"
		__root_or_deprecated "$_user" || __root_or_deprecated "$_group" || eval "$2=no"
	}

	[ "$_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: No whitelist file."
		return 1
	}

	_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 ]
}