#!/bin/bash
# Copyright 2017 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

set -e

# Do not proceed unless maas-proxy.conf exists.
if [ ! -e "$SNAP_DATA/proxy/maas-proxy.conf" ]; then
    echo "Cannot start squid as $SNAP_DATA/proxy/maas-proxy.conf does not exist."
    exit 1
fi

# Ensure that the cache is initialized.
if [ ! -d "$SNAP_COMMON/proxy/cache/00" ]; then
    $SNAP/usr/sbin/squid -z -N -f "$SNAP_DATA/proxy/maas-proxy.conf"
fi

# Start squid, force kill it when the script is terminated. Squid sometimes
# (most of the time) just does not want to die.
trap 'kill -9 $PID; wait $PID' TERM INT
$SNAP/usr/sbin/squid -N -d 5 -f "$SNAP_DATA/proxy/maas-proxy.conf" &
PID=$!
wait $PID
