#!/bin/bash
set -eux

# Some templates explictly pass completion-handle/completion-signal in the
# StructuredConfig data, if we find a handle, send a completion signal
# Note, this for backwards compatibility, in general the logic below should be
# used instead, where a per-deployment signal is sent using the handle provided
# automatically by heat
HANDLE=$(os-apply-config --key completion-handle --type raw --key-default "")
SIGNAL=$(os-apply-config --key completion-signal --type raw --key-default "")
ID=$(os-apply-config --key instance-id --type raw --key-default "")

[ -n "$ID" ] || exit 0

call_curl() {
    local method=$1
    local url=$2
    local output=$(mktemp)
    status=$(curl -s -w %{http_code} -X $method -H 'Content-Type:' -o $output --data-binary "{\"Status\" : \"SUCCESS\",\"Reason\" : \"Configuration Complete\",\"UniqueId\" : \"$ID\",\"Data\" : \"Finished os-refresh-config.\"}" $url)
    cat $output
    rm $output
    if [ "$status" != "200" ]; then
        exit 1
    fi
}

# Signals use POST, wait handles use PUT
if [ -n "$HANDLE" ]; then
    call_curl PUT $HANDLE
fi
if [ -n "$SIGNAL" ]; then
    call_curl POST $SIGNAL
fi

# This extracts "deploy_signal_id" from any deployments of group "os-apply-config"
# deploy_signal_id is a pre-signed URL when CFN_SIGNAL is specified, it's not
# included if NO_SIGNAL is specified.  Won't yet work with HEAT_SIGNAL.
DEPLOYMENT_HANDLES=$(os-apply-config --key deployments --type raw --key-default "" | \
                     jq -r "map(select(.group == \"os-apply-config\") | .inputs | \
                            map(select(.name == \"deploy_signal_id\"))) | .[][].value")
for url in ${DEPLOYMENT_HANDLES}
do
    echo "Signalling deploy_signal_handle=$url"
    call_curl POST $url
done
