#!/bin/bash

# Created by jiaqiang.ye@lnxall.com
# 2024/01/17
# simple file certificate generate script

KEY_PEM=
VERIFY_APP=
TARGET_FILE="$1"

check_keypem() {
	local KEY_DIR=$(realpath "$1")
	[ -n "${KEY_DIR}" ] && KEY_DIR=$(dirname "${KEY_DIR}")

	local keyfile="${KEY_DIR}/key.pem"
	if [ ! -f "${keyfile}" ] ; then
		echo "Error, private key not found: ${keyfile}" 1>&2
		return 1
	fi

	local perm=$(ls -l ${keyfile} | awk '{print $1}')
	if [ -z "${perm}" ] ; then
		echo "Error, cannot stat '${keyfile}'." 1>&2
	elif [ "${perm}" != "-r--------" ] ; then
		chmod 400 "${keyfile}"
	fi

	declare -g KEY_PEM=${keyfile}
	declare -g VERIFY_APP=${KEY_DIR}/lnxall_verify
	return 0
}

sign_file() {
	if [ -z "${TARGET_FILE}" ] ; then
		echo "Error, file to be signed not specified." 1>&2
		return 1
	fi

	if [ ! -f "${TARGET_FILE}" ] ; then
		echo "Error, file to be signed not found." 1>&2
		return 2
	fi

	${VERIFY_APP} "${TARGET_FILE}" >/dev/null 2>/dev/null
	if [ $? -eq 0 ] ; then
		echo "File already signed with certificate: ${TARGET_FILE}"
		return 0
	fi

	local signout=rsa-sha256.sign
	rm -rf ${signout} # remove existing generated certificate
	# RSA certificate signing command from:
	#     https://pagefault.blog/2019/04/22/how-to-sign-and-verify-using-openssl/
	openssl dgst -sign ${KEY_PEM} -keyform PEM -sha256 \
		-out ${signout} -binary "${TARGET_FILE}"
	if [ $? -ne 0 ] ; then
		rm -rf ${signout}
		echo "Error, failed to sign file with RSA/SH256: ${TARGET_FILE}" 1>&2
		return 3
	fi

	# append certificate to file
	echo "Appending certificate data to ${TARGET_FILE}"
	cat "${signout}" >> ${TARGET_FILE}
	return $?
}

check_keypem "$0" || exit 1
sign_file ; exit $?
