#!/bin/bash -e
#
# enable-firewall - Called by systemd to setup a proper firewall for Whonix
#                   gateway, workstation or template
#
# Copyright (C) 2014 - 2015 Jason Mehring <nrgaway@gmail.com>
# License: GPL-2+
# Authors: Jason Mehring
#
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public License
#   as published by the Free Software Foundation; either version 2
#   of the License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

#set -x

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

if ! test -f /run/qubes/this-is-templatevm ; then
   exit 0
fi

who_ami="$(whoami)"

if [ ! "${who_ami}" = "updatesproxycheck" ]; then
   printf '%s\n' "$0: ERROR: This script is expected to be run under user updatesproxycheck by
/lib/systemd/system/qubes-whonix-torified-updates-proxy-check.service
Instead this script is running under user '${who_ami}'." >&2
   exit 1
fi

signal_sigterm() {
   exit 143
}

trap "signal_sigterm" SIGTERM

exithandler() {
   touch -- /run/updatesproxycheck/whonix-secure-proxy-check-done
}

trap "exithandler" EXIT

if [ -e /run/qubes-service/skip-torified-updates-proxy-check ]; then
   touch -- /run/updatesproxycheck/whonix-secure-proxy
fi

if [ -e /run/updatesproxycheck/whonix-secure-proxy ]; then
   exit 0
fi

safe-rm -f -- /run/updatesproxycheck/whonix-secure-proxy-check-done

source /usr/lib/qubes-whonix/utility_functions.sh

## Since curl does not timeout, handling timeout is left to the systemd unit.
while true; do
   ## Check if a secure Tor update server is available
   if curl_output="$(UWT_DEV_PASSTHROUGH="1" curl --silent -- "${PROXY_SERVER}")" ; then
      if printf '%s\n' "${curl_output}" | grep -q -- "${PROXY_META}" ; then
          touch -- /run/updatesproxycheck/whonix-secure-proxy
          printf '%s\n' "$0: INFO: Success."
          exit 0
      fi
      printf '%s\n' "\
$0: ERROR: PROXY_SERVER reachable but does not contain PROXY_META.
$0: Debugging information:
PROXY_SERVER: ${PROXY_SERVER}
PROXY_META: ${PROXY_META}
curl_output: ${curl_output}" >&2
      exit 1
   fi
   sleep -- 1
done
