#!/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
}

call_curl_deployment() {
    local method=$1
    local url=$2
    local stdout=$3
    local output=$(mktemp)
    status=$(curl -s -w %{http_code} -X $method -H 'Content-Type:' -o $output --data-binary "{\"deploy_stdout\": \"$stdout\", \"deploy_status_code\": \"0\"}" $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.
# We also include the id, which provides a means to identify when a config
# being deployed has changed.  DEPLOYMENTS is a list of concatenated ID+URL.
#
# The jq is really hard to read, so here's the process line by line:
# 1. Extract all deployments data via os-apply-config
# 2. Select all which have a config group of "os-apply-config"
# 3. Filter further for only deployments with a deploy_signal_id input
#    thus avoiding NO_SIGNAL deployments
# 4. Extract and join the "id" key and the input value for deploy_signal_id
# 5. Print the elements of the resulting list to enable for loop iteration
DEPLOYMENTS=$(os-apply-config --key deployments --type raw --key-default "" |
              jq -r "map(select(.group == \"os-apply-config\") |
              select(.inputs[].name == \"deploy_signal_id\") |
              .id + (.inputs | map(select(.name == \"deploy_signal_id\")) | .[].value)) |
              .[]")

# We store a file per deployment similar to how heat-config stores them under
# /var/lib/heat-config/deployed, here we use /var/lib/os-apply-config-deployments/deployed
DEPLOYED_DIR="/var/lib/os-apply-config-deployments/deployed"
if [ ! -d $DEPLOYED_DIR ]; then
    mkdir -p $DEPLOYED_DIR
fi

for dep  in ${DEPLOYMENTS}
do
    DEPLOY_ID=$(echo $dep | sed "s/http.*$//")
    DEPLOY_URL=$(echo $dep | sed "s/^.*http/http/")
    if [ ! -f $DEPLOYED_DIR/$DEPLOY_ID ]; then
        echo "Signalling os-apply-config deployment $DEPLOY_ID $DEPLOY_URL"
        call_curl_deployment POST $DEPLOY_URL "os-apply-config deployment $DEPLOY_ID completed"
        touch $DEPLOYED_DIR/$DEPLOY_ID
    else
        echo "Skipping $DEPLOY_ID, already deployed"
    fi
done
