#!/bin/bash
set -eux

PROXY_IP=""
PROXY_PORT=""


status-set maintenance "Checking config" || true
PROPOSED_PACKAGES="$(config-get proposed-packages)"
if [[ "$PROPOSED_PACKAGES" != "" ]]; then
    status-set maintenance "Disabling firewall to install packages" || true
    UFW_STATUS=$(ufw status | cut -d ' ' -f2)
    ufw disable
    status-set maintenance "Installing packages from the proposed archive" || true
    RELEASE=$(lsb_release -sc)
    apt-get update
    apt-get install -y -t $RELEASE-proposed $PROPOSED_PACKAGES
    status-set maintenance "Packages installed" || true
    if [[ $UFW_STATUS == "active" ]]; then
        status-set maintenance "Enabling the firewall" || true
        ufw --force enable
    fi
fi

status-set maintenance "Checking proxy." || true
set +e
# This is a hack. We don't want to iterate, but we need to
# because we need the state of relations and config to know
# if this charm is active or something else.
for app in $(relation-ids forwardproxy); do
    for unit in $(relation-list -r $app); do
        PROXY_IP="$(relation-get -r $app ip $unit)"
        PROXY_PORT="$(relation-get -r $app port $unit)"
    done
done
set -e

if [[ "$PROXY_IP" == "" || "$PROXY_PORT" == "" ]]; then
    status-set maintenance "Removing firewall rules" || true
    echo "PATH="$PATH"" > /etc/environment
    status-set waiting "Waiting for forwardproxy" || true
    exit 0
fi

# LXD was given the 10.0.8.* by scripts/setup-lxd.sh
LXD_ADDRESSES="$(echo 10.0.8.{1..255} | sed 's/ /,/g')"
EXTRA_NO_PROXY="$(config-get extra-no-proxy | sed -e 's/ /,/g')"
NO_PROXY="localhost,127.0.0.1,$EXTRA_NO_PROXY,$LXD_ADDRESSES"
status-set maintenance "Updating proxy rules." || true
cat > /etc/environment << EOF
PATH="$PATH"
http_proxy=http://$PROXY_IP:$PROXY_PORT/
https_proxy=http://$PROXY_IP:$PROXY_PORT/
ftp_proxy=http://$PROXY_IP:$PROXY_PORT/
no_proxy=$NO_PROXY
HTTP_PROXY=http://$PROXY_IP:$PROXY_PORT/
HTTPS_PROXY=http://$PROXY_IP:$PROXY_PORT/
FTP_PROXY=http://$PROXY_IP:$PROXY_PORT/
NO_PROXY=$NO_PROXY
EOF
status-set active "Updated proxy rules" || true
