#!/bin/bash

set -e
set -u

script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
source "$script_dir/functions"

export LC_ALL=C

martools_dir=/home/signing-mar/mar-tools
if ! test -d "$martools_dir"; then
  >&2 echo "Please create $martools_dir"
  exit 3
fi
export LD_LIBRARY_PATH="$martools_dir"
export PATH="$martools_dir:$PATH"

# Prompt for the NSS password.
# TODO: Test that the entered NSS password is correct.  But how?  Unfortunately,
# both certutil and signmar keep trying to read a new password when they are
# given an incorrect one.
test -n "${NSSPASS:-}" || read -s -p "NSS password:" NSSPASS
echo ""

COUNT=0
cd ~/"$SIGNING_PROJECTNAME-$tbb_version"
for marfile in *.mar; do
  if [ ! -f "$marfile" ]; then
    continue;
  fi

  # First, we check for an existing signature.  The signmar -T output will
  # include a line like "Signature block found with N signatures".
  SIGINFO_PREFIX="Signature block found with "
  SIGINFO=$(signmar -T "$marfile" | grep "^${SIGINFO_PREFIX}")
  SIGCOUNT=0
  if [ ! -z "$SIGINFO" ]; then
    SIGCOUNT=$(echo $SIGINFO | sed -e "s/${SIGINFO_PREFIX}//" -e 's/\([0-9]*\).*$/\1/')
  fi
  if [ $SIGCOUNT -ne 0 ]; then
    echo "Skipping $marfile (already signed)"
    continue;
  fi

  echo "$NSSPASS" | sudo -u signing-mar -- "$wrappers_dir/sign-mar" "$marfile"
  cp /home/signing-mar/last-signed-mar.mar "$marfile"
  COUNT=$((COUNT + 1))
  echo "Signed MAR file $COUNT ($marfile)"
done

echo "$COUNT MAR files have been signed."
