#!/usr/bin/env bash
set -ex

source $SNAP/actions/common/utils.sh
use_snap_env

if ! [ -e "$SNAP_DATA/var/lock/clustered.lock" ]; then
  echo "Not a worker node, exiting"
  exit 0
fi

if ! [ -e "$SNAP_DATA/args/traefik" ]
then
  exit 0
fi

if ! [ -e "$SNAP_DATA/args/apiserver-proxy" ]
then
  exit 0
fi

sed 's@${SNAP}@'"${SNAP}"'@g;s@${SNAP_DATA}@'"${SNAP_DATA}"'@g' $SNAP_DATA/args/traefik/traefik-template.yaml > $SNAP_DATA/args/traefik/traefik.yaml

# This is really the only way I could find to get the args passed in correctly.
declare -a args="($(cat $SNAP_DATA/args/apiserver-proxy))"
exec "$SNAP/bin/cluster-agent" apiserver-proxy "${args[@]}"
