#!/bin/bash
set -eux

status-set maintenance "Getting dstdomain" || true
SITENAMES="$(config-get sitenames)"
PORT="$(config-get port)"
IP="$(unit-get private-address)"
LOCALNET=""

# Create a "localnet" rule for all addresses that can use this proxy.
for app in $(relation-ids forwardproxy); do
    for unit in $(relation-list -r $app); do
        addr="$(relation-get -r $app private-address $unit)"
        if [[ "$addr" != "" ]]; then
            LOCALNET="$LOCALNET\nacl localnet src $addr"
        fi
    done
done
LOCALNET="$(echo -e $LOCALNET)"
# Create the squid conf that is included in the default conf.
cat > /etc/squid/forwardproxy.conf << EOF
http_port $PORT
$LOCALNET
http_access allow localnet
EOF

service squid restart || service squid start

if [[ -z $SITENAMES ]]; then
    status-set active "Proxying: *" || true
else
    status-set active "Proxying: $SITENAMES" || true
fi

# Update the proxy-ees with the necessary config.
if [[ $0 != 'config-changed' ]]; then
    for relation_id in $(relation-ids forwardproxy); do
        relation-set -r $relation_id ip="$IP" port="$PORT"
    done
fi
