#!/bin/bash
#
#
# You may set NSS_DB_DIR and/or NSS_CERTNAME before invoking this script
# (if you don't want to use the default values).

set -e
set -u

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

if [ -z "${NSS_DB_DIR+x}" ]; then
  NSS_DB_DIR=/home/boklm/marsigning/nssdb7
fi

if [ -z "${NSS_CERTNAME+x}" ]; then
  NSS_CERTNAME=marsigner
fi

export LC_ALL=C

# Check some prerequisites.
if [ ! -r "$NSS_DB_DIR/cert9.db" ]; then
  >&2 echo "Please create and populate the $NSS_DB_DIR directory"
  exit 2
fi

# Extract the MAR tools so we can use the signmar program.
MARTOOLS_TMP_DIR=$(mktemp -d)
trap "rm -rf $MARTOOLS_TMP_DIR" EXIT
MARTOOLS_ZIP=~/gitian-builder/inputs/mar-tools-new-linux32.zip
unzip -d "$MARTOOLS_TMP_DIR" -q "$MARTOOLS_ZIP"
export PATH="$MARTOOLS_TMP_DIR/mar-tools:$PATH"
if [ -z "${LD_LIBRARY_PATH+x}" ]; then
  export LD_LIBRARY_PATH="$MARTOOLS_TMP_DIR/mar-tools"
else
  export LD_LIBRARY_PATH="$MARTOOLS_TMP_DIR/mar-tools:$LD_LIBRARY_PATH"
fi

# 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 ~/"$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" | signmar -d "$NSS_DB_DIR" -n "$NSS_CERTNAME" -s \
    "$marfile" tmp.mar
  mv -f tmp.mar "$marfile"
  COUNT=$((COUNT + 1))
  echo "Signed MAR file $COUNT ($marfile)"
done

echo "$COUNT MAR files have been signed."
