#!/bin/bash

callee=$1; shift
service=$1; shift
acl=$1; shift

cmd=$1; shift
host=$1; shift

msg() {
  if [ -z "$QUIET" ]; then
    echo "$@"
  fi
}

usage() {
  msg "Usage: $callee <list|add <host>|del <host>>|clear"
  exit 1
}

if [ -z "$cmd" ]; then
  cmd="list"
fi

case "$cmd" in
  list)
    msg "Hosts allowed to reach $service:"
    haproxy-acl show "$acl"
    ;;

  add)
    if [ -z "$host" ]; then
      msg "Usage: $callee add <host>"
      exit 2
    fi

    msg "Adding host $host to $service"
    haproxy-acl add "$acl" "$host"

    exec $callee list
    ;;

  del)
    if [ -z "$host" ]; then
      msg "Usage: $callee del <host>"
      exit 2
    fi

    msg "Removing host $host from $service"
    haproxy-acl del "$acl" "$host"

    exec $callee list
    ;;

  clear)
    $callee list

    echo -n "Do you want to clear the list? [Y/N] "
    read ans

    if [[ "$ans" =~ [yY] ]]; then
      haproxy-acl clear "$acl"
    fi

    exec $callee list
    ;;

  *)
    usage
    ;;
esac
