#!/bin/bash
# Here do anything needed to install the service
# e.g. apt install -y foo
# Make sure this hook exits cleanly and is idempotent.
set -x

source inc/common

GATEWAY="$( config-get gateway )"

if [ -z "$GATEWAY" ]; then
    juju-log "Gateway option is empty. Blocking and doing nothing."
    status-set blocked "No gateway specified."
    exit 0
fi

GATEWAY_IP="$( echo "$GATEWAY" | awk -F "/" '{print $1}' )"

DEFAULTROUTECOMMAND="$( getdefaultroutecommand )"

if [ $(eval $DEFAULTROUTECOMMAND | wc -l ) -eq 1 ] && eval $DEFAULTROUTECOMMAND | grep "\<${GATEWAY_IP}\>"; then
    juju-log "Default gateway looks OK. Doing nothing."
    exit 0
fi

juju-log "Default gateway doesn't look good. Setting the default gateway.."

status-set maintenance "Setting the default gateway"

# copy metric 0 routes to routes with metric 1
copy0metricroutes "$DEFAULTROUTECOMMAND"

# delete metric 0 routes
delete0metricroutes "$DEFAULTROUTECOMMAND"

# add our route
if setdefaultgateway "$GATEWAY_IP"; then
    juju-log "Default gateway set"
    status-set active "Unit is ready"
else
    juju-log "Route change failed. Exiting..."
    status-set blocked "Incorrect gateway IP."
fi