#!/bin/bash -e
# vim: set ts=4 sw=4 sts=4 et :
#
# 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

qubes_vm_type="$(qubesdb-read /qubes-vm-type)"

if [ ! "$qubes_vm_type" = "TemplateVM" ]; then
   exit 0
fi

signal_sigterm() {
   exit 143
}

trap "signal_sigterm" SIGTERM

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

trap "exithandler" EXIT

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

rm -f /run/qubes-service/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="$(sudo -u updatesproxycheck UWT_DEV_PASSTHROUGH="1" curl --silent "${PROXY_SERVER}")" ; then
      if echo "$curl_output" | grep -q "${PROXY_META}" ; then
          touch /run/qubes-service/whonix-secure-proxy
      fi
      break
   fi
   sleep 1
done
