#!/bin/sh

set -o errexit  # (-e) exit immediately if any command has a non-zero exit status
set -o nounset  # (-u) don't accept undefined variables
#set -o xtrace  # for debugging

input="${1:-}"

if [ -z "$input" ]; then
  >&2 echo "The path to Lagrange's trust store must be provided."
  >&2 echo "The default on GNU/Linux is ~/.config/lagrange/trusted.2.txt"
  exit 1
fi

dir="$(dirname "$0")"  # directory where this script is

# Read the script-generated trust store.
# If input ends with "trusted.txt", then use the old trust store format.
if echo "$input" | grep -q trusted\\.txt$; then
  trust_store=$(cat "$dir/trusted.txt")
else
  trust_store=$(cat "$dir/trusted.2.txt")
fi

# Loop through user's trust store.
while read -r line; do

  entry=$(echo "$line" | cut -d ' ' -f 1)

  # If this entry is not in the script-generated trust store, add it.
  if ! echo "$trust_store" | grep -qF "$entry"; then
    trust_store="$trust_store\n$line"
  fi

done < "$input"

# Output to stdout.
echo "$trust_store"
