#!/usr/bin/env bash

. lib.bash || exit

cert=""
nssdb="sql:$HOME/.pki/nssdb"
force=0

have pesign    || err "missing 'pesign' tool"
(( ! errors )) || exit

while getopts ":c:d:f" OPT; do
	case $OPT in
	c) cert=$OPTARG;;
	d) nssdb=$OPTARG;;
	f) force=1;;
	*) lib:die_getopts;;
	esac
done; shift $((OPTIND-1))

if [[ ! $cert ]]; then
	die "certificate name not specified"
fi

in_file=$1

if [[ ! $in_file ]]; then
	die "input file not specified"
fi

if [[ ! -f $in_file ]]; then
	die "input file '$in_file' does not exist"
fi

out_file=${in_file%.*}-signed.${in_file##*.}

if [[ -e $out_file ]] && (( ! force )); then
	die "output file '$out_file' already exists"
fi

pesign --verbose \
	--certdir="$nssdb" \
	--certficate="$cert" \
	--in="$in_file" \
	--out="$out_file" \
	--sign

lib:echo "Created \"$out_file\""
