#!/bin/bash

## Copyright (C) 2020 - 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

# shellcheck source=../../../../kicksecure/helper-scripts/usr/libexec/helper-scripts/has.sh
## Sibling repo: absent in an isolated CI checkout, so shellcheck cannot
## follow it there. The source= path above still documents where it lives.
##
## TODO: Only run shellcheck in a full derivative-maker source tree.
# shellcheck disable=SC1091
source /usr/libexec/helper-scripts/has.sh
## Provides validate_safe_filename, used on profile_name below.
# shellcheck source=../../../../kicksecure/helper-scripts/usr/libexec/helper-scripts/strings.bsh
##
## TODO: See above TODO.
# shellcheck disable=SC1091
source /usr/libexec/helper-scripts/strings.bsh
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

has mkdir unlink ln

SCRIPTNAME="$(basename "${BASH_SOURCE[0]}")"

if [ "$(id -u)" != "0" ]; then
    printf '%s\n' "ERROR: This must be run as root (sudo)!"
    printf '%s\n' "INFO: You can start ${SCRIPTNAME} by entering..."
    printf '%s\n' "      sudo ${SCRIPTNAME}"
    exit 1
fi

profile_name="${1:-}"

if [ "${profile_name}" = "" ]; then
   printf '%s\n' "ERROR: syntax: sudo ${SCRIPTNAME} profile-name"
   exit 1
fi

if ! validate_safe_filename profile_name ; then
   printf '%s\n' "ERROR: invalid profile name: '${profile_name}'" >&2
   exit 1
fi

profile_file_source=""

if [ -f "/usr/share/doc/onion-grater-merger/examples/${profile_name}.yml" ]; then
   profile_file_source="/usr/share/doc/onion-grater-merger/examples/${profile_name}.yml"
else
   for file_name in "/usr/share/doc/onion-grater-merger/examples/"*"_${profile_name}.yml" ; do
      ## prefer /usr/share/doc/onion-grater-merger/examples/50_onionshare.yml
      ## over   /usr/share/doc/onion-grater-merger/examples/40_onionshare.yml
      profile_file_source="${file_name}"
   done
fi

if [ ! -f "${profile_file_source}" ]; then
   printf '%s\n' "ERROR: profile_file_source '${profile_file_source}' does not exist!"
   exit 1
fi

profile_file_source_base_name="$(basename "${profile_file_source}")"
profile_file_target="/usr/local/etc/onion-grater-merger.d/${profile_file_source_base_name}"

mkdir -p /usr/local/etc/onion-grater-merger.d/

unlink "${profile_file_target}" &>/dev/null || true

ln -s "${profile_file_source}" "/usr/local/etc/onion-grater-merger.d/"

systemctl --no-block --no-pager restart onion-grater

printf '%s\n' "OK: Added profile_file_source: '${profile_file_source}'."
printf '%s\n' "OK."
