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

removed=""

if [ -f "/usr/local/etc/onion-grater-merger.d/${profile_name}.yml" ]; then
   profile_file_target="/usr/local/etc/onion-grater-merger.d/${profile_name}.yml"
   if unlink "${profile_file_target}" &>/dev/null ; then
      removed=true
      printf '%s\n' "OK: Removed profile_file_target: '${profile_file_target}'."
   fi
else
   for file_name in "/usr/local/etc/onion-grater-merger.d/"*"_${profile_name}.yml" ; do
      profile_file_target="${file_name}"
      if unlink "${profile_file_target}" &>/dev/null ; then
         removed=true
         printf '%s\n' "OK: Removed profile_file_target: '${profile_file_target}'."
      fi
   done
fi

if [ "${removed}" = "true" ]; then
   systemctl --no-block --no-pager restart onion-grater
else
   printf '%s\n' "OK: None removed. (Maybe already removed?)"
   printf '%s\n' "OK."
fi
