#!/bin/bash
set -e
set -o pipefail
# for debugging
# set -x

help()
{
    echo
    echo "$0: disables egress proxy for a given app."
    echo "Syntax: disable-egress <APP>"
    echo "  <APP> must be a valid cf app in the current space with egress enabled."
    #echo "Options:"
    #echo "  --space <SPACE>: #TODO"
    echo
    echo "To re-enable egress for an app, use enable-egress."
    exit 1
}

app="$1"

if [ -z "$app" ]; then
    echo "No app provided."
    help
else
    echo "Checking for app $app in space.."
    if cf apps | tr -s ' ' | cut -d ' ' -f 1 | grep -q -E "(^|\s)$app($|\s)"; then
        echo "$app found."
        echo "Unsetting environment variable proxy_url.."
        cf unset-env "$app" proxy_url
        echo "Checking network policy.."
        read -r source dest protocol port space <<< "$( cf network-policies --source "$app" | tail -n +4 | tr -s ' ' | cut -d ' ' -f 1-5 )"
        if [ -z "$dest" ] && [ -z "$protocol" ] && [ -z "$port" ] &&  [ -z "$space" ]; then
            # network policy already empty, pass
            echo "Network policy not found, continuing.."
        else
            cf remove-network-policy "$source" "$dest" -s "$space" --protocol "$protocol" --port "$port"
        fi
        echo "Restarting $app.."
        cf restart "$app"
    else
        echo "App not found in space."
        help
    fi
fi
