#!/bin/sh
##
##  consul-acl-update.sh -- Update Consul ACL
##

#   parse command line options
opt_mt=""
opt_id=""
opt_name="Client"
opt_type="client"
while [ ".$1" != . ]; do
    case "$1" in
        -m ) opt_mt="$2";   shift; shift ;;
        -i ) opt_id="$2";   shift; shift ;;
        -n ) opt_name="$2"; shift; shift ;;
        -t ) opt_type="$2"; shift; shift ;;
        *  ) break ;;
    esac
done
if [ $# -ne 1 ]; then
    echo "Usage: consul-acl-update [-m <master-token>] [-i <id>] [-n <name>] [-t <type>] <policy-file>"
    exit 1
fi
policy_file="$1"
if [ ! -f "$policy_file" ]; then
    echo "$0: ERROR: no such policy file \"\$policy_file\""
    exit 1
fi

#   determine ACL master token
if [ ".$opt_mt" = . ]; then
    opt_mt=`(grep '^acl_master_token' @l_prefix@/etc/consul/consul.hcl) 2>/dev/null |\
        @l_prefix@/bin/sed -e 's;^.*"\(.*\)";\1;'`
    if [ ".$opt_mt" = . ]; then
        echo "$0: ERROR: unable to determine Consul ACL master token (use option -m to specify manually)"
        exit 1
    fi
fi

#   determine ACL id (aka client token)
if [ ".$opt_id" = . ]; then
    opt_id=`@l_prefix@/bin/uuid -v4`
fi

#   determine ACL client rules
policy=`cat "$policy_file" | \
    @l_prefix@/bin/sed ':a;N;$!ba;s/\n/ /g' | \
    @l_prefix@/bin/sed -e '/^ *$/d' -e 's;  *; ;g' -e 's;^ *;;' -e 's; *$;;'`

#   create/update ACL client token
@l_prefix@/bin/jq -n \
    --arg id     "$opt_id" \
    --arg name   "$opt_name" \
    --arg type   "$opt_type" \
    --arg policy "$policy" \
    '{ "ID": $id, "Name": $name, "Type": $type, "Rules": $policy }' | \
    @l_prefix@/bin/curl -k -s -S -X PUT -d @- \
        "http://127.0.0.1:8500/v1/acl/update?token=$opt_mt" | \
        @l_prefix@/bin/jq -r ".ID"

