#!/usr/bin/env bash

set -o pipefail || exit 1

declare -A module_versions
module_versions["$1"]="$2"
id=$3
remote_server=$4

deploy_log_file=/var/log/deploy_"$id".log
# Redirect stdout and stderr to a process(subshell) running an append tee for
# deploy_id.log (This file gets deleted once deployment is finished).
# Forward the logs to Lighthouse syslog service and also locally.
tag='[deployment]'
exec &> >(tee >(logger -n "$remote_server" -t "$tag") >(logger -t "$tag") | tee -ai "$deploy_log_file")

function cleanup {
    exit_code="$?"
    trap - EXIT

    if ! rmdir /tmp/deploy.lock; then
        echo "Failed to remove the deployment process lock directory"
        exit_code=1
    fi

    exit "$exit_code"
}
trap cleanup EXIT HUP INT QUIT PIPE TERM

echo "Starting Deployment of modules" \
&& res=0 \
&& lh_vpn_interface="$( ssh "$LH_SSH_USERNAME"@"$LH_HOST_ADDRESS" "ip -family inet -oneline addr show | grep -- \$(infod_client -o get -p openvpn.lhvpn.address -q) | cut -d' ' -f2" )" \
&& [ ! -z "$lh_vpn_interface" ] \
&& lh_vpn_address="$( ssh "$LH_SSH_USERNAME"@"$LH_HOST_ADDRESS" "( export IFS=' ' && printf '%s ' \$( ip -f inet -o address show dev $lh_vpn_interface ) ) | cut -d ' ' -f 4 | cut -d '/' -f 1" )" \
&& [[ "$lh_vpn_address" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] \
&& for module_id in "${!module_versions[@]}"; do
    version="${module_versions[${module_id}]}" \
    && echo "Deploying $module_id-v$version..." \
    && extra_vars="$( jq -n -M -c -a \
        --arg lh_host_address "$LH_HOST_ADDRESS" \
        --arg lh_ssh_username "$LH_SSH_USERNAME" \
        --arg lh_vpn_interface "$lh_vpn_interface" \
        --arg lh_vpn_address "$lh_vpn_address" \
        --arg module_name "$module_id" \
        --arg module_version "$version" \
        '{
            "lh_host_address": $lh_host_address,
            "lh_ssh_username": $lh_ssh_username,
            "lh_vpn_interface": $lh_vpn_interface,
            "lh_vpn_address": $lh_vpn_address,
            "module_name": $module_name,
            "module_version": $module_version
        }' )" \
    && ansible-playbook "/ansible/${module_id}_${version}.yml" --extra-vars "$extra_vars" 2>&1 \
    || res="$?"
    # NOTE continuing regardless of any error (partial error cases still cause failure though)
done \
|| res="$?"

# write the exit_code to the deploy status file
echo "$res" > "/tmp/.${id}"

if [[ "$res" != "0" ]]; then
    echo "Deployment of modules failed"
    exit 1
fi

echo "Complete!"
exit "$res"
