#!/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

if [ -z "${1:-}" ]; then
  >&2 echo "The path to the user's trust store must be provided."
  >&2 echo "The default on GNU/Linux is ~/.cache/amfora/tofu.toml"
  exit 1
fi

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

trust_store=$(cat "$dir/tofu.toml")  # script-generated trust store

# 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 < "${1:-}"

# Output to stdout.
echo "$trust_store"
