#!/bin/bash

## Copyright (C) 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

#set -x

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose
shopt -s nullglob

error_handler() {
   local exit_code="$?"
   printf '%s\n' "ERROR: exit_code: ${exit_code} | BASH_COMMAND: ${BASH_COMMAND}"
   exit 1
}

trap error_handler ERR

## Pre-existing: assigned for consistency with the sibling scripts but not
## referenced here.
# shellcheck disable=SC2034
SCRIPTNAME="$(basename "${BASH_SOURCE[0]}")"

print_profile(){
  if [ "${show}" = "--show" ]; then
    printf '%s\n' "===================================================================="
    printf '%s\n' "BEGIN PROFILE: ${profile}"
    printf '%s\n' "--------------------------------------------------------------------"
    cat "${profile}"
    printf '%s\n' "--------------------------------------------------------------------"
    printf '%s\n' "END PROFILE: ${profile}"
    printf '%s\n' "===================================================================="
  else
    printf '%s\n' "${profile}"
  fi
}

usage(){
  printf '%s\n' "usage: ${0##*/}: --available|--used [--show]"
  exit 0
}

option="${1:-}"
show="${2:-}"

if [ "${option}" = "--used" ]; then
  for profile in \
    /etc/onion-grater-merger.d/*.yml \
    /usr/local/etc/onion-grater-merger.d/*.yml
  do
    printf '%s\n' "${profile}" | grep -F "*" && continue
    print_profile
  done
elif [ "${option}" = "--available" ]; then
  for profile in \
    /usr/share/doc/onion-grater-merger/examples/*.yml
  do
    printf '%s\n' "${profile}" | grep -F "*" && continue
    print_profile
  done
else
  usage
fi
