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

set -x
set -e

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
   echo "$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 command -v qubesdb-read &>/dev/null ; then
   [ -n "$dns_server" ] || dns_server="$(qubesdb-read /qubes-primary-dns)"
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"
