#!/bin/bash

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

#### meta start
#### project Whonix
#### category tor
#### gateway_only yes
#### description
## TODO
#### meta end

## $1 is either:
## add
## remove

## xtrace is this script's user-visible reporting mechanism.
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/as_root.sh
## TODO: Only run shellcheck when in a full derivative-maker source tree.
# shellcheck disable=SC1091
source /usr/libexec/helper-scripts/as_root.sh
# shellcheck source=../../../../kicksecure/helper-scripts/usr/libexec/helper-scripts/has.sh
# shellcheck disable=SC1091
source /usr/libexec/helper-scripts/has.sh

as_root

start_marker="## START-autogenerated-by-edit-etc-torrc-conf-START"
end_marker="## END-autogenerated-by-edit-etc-torrc-conf-END"

remove_autogenerated() {
   ## Delete lines between start_marker and end_marker.
   sed -i "/${start_marker}/,/${end_marker}/{//!d;s/ ,$//}" /etc/resolv.conf

   ## https://github.com/Samer-Al-iraqi/Linux-str_replace/issues/8
   #str_replace "${start_marker}" "" /etc/resolv.conf >/dev/null
   #str_replace "${end_marker}" "" /etc/resolv.conf>/dev/null

   ## Delete start_marker and end_marker.
   ## https://stackoverflow.com/questions/66992027/remove-whole-line-inducing-its-line-break-from-a-file
   sed -i "/${start_marker}/d" /etc/resolv.conf
   sed -i "/${end_marker}/d" /etc/resolv.conf
}

if ! test -e /etc/resolv.conf ; then
   touch /etc/resolv.conf
fi

if ! test -w /etc/resolv.conf ; then
   printf '%s\n' "$0: ERROR: /etc/resolv.conf not writeable!" >&2
   exit 1
fi

if [ "${1:-}" = "remove" ]; then
   remove_autogenerated
   true "INFO: remove OK."
   exit 0
fi

if has qubesdb-read ; then
   [ -n "${dns_server:-}" ] || dns_server="$(qubesdb-read /qubes-primary-dns || true)"
   if [ "${dns_server}" = "" ]; then
      printf '%s\n' "$0: ERROR: qubesdb-read /qubes-primary-dns returned nothing." >&2
      ## Let's not tell the user "Set dns_server= to override", so that they
      ## don't break things trying to work around a bug the wrong way.
      printf '%s\n' "$0: ERROR: Refusing to guess a nameserver on Qubes." >&2
      exit 1
   fi
else
   ## see /etc/resolv.conf
   [ -n "${dns_server:-}" ] || dns_server="10.0.2.3"
fi

line_to_add_maybe="nameserver ${dns_server}"

if grep -q -- "^${line_to_add_maybe}\$" /etc/resolv.conf ; then
   true "INFO: No need to add. line_to_add_maybe already in /etc/resolv.conf."
   exit 0
fi

true "INFO: Need to add line_to_add_maybe."

remove_autogenerated

comment="\
##
## generated by $0
##"

etc_resolv_conf_addition="\
${start_marker}
${comment}
${line_to_add_maybe}
${end_marker}"

## provided by: helper-scripts
append-once /etc/resolv.conf "${etc_resolv_conf_addition}"

true "INFO: add OK"
