#!/bin/bash
set -e
set -o pipefail

SCRIPTDIR="$( dirname --  $(realpath "${BASH_SOURCE}"); )";
RG=$(jq -r .azureresourcegroup constellation-state.json)
SUBNET=$(jq -r .azuresubnet constellation-state.json)
VNET=${SUBNET%"/subnets/nodeNetwork"}
PUBKEY=$(cat ~/.ssh/id_rsa.pub)
DEPLOYMENT_NAME=jump-host
VM_NAME=jump-host

az deployment group create \
    -o none \
    --name "${DEPLOYMENT_NAME}" \
    --resource-group "${RG}" \
    --template-file "${SCRIPTDIR}/template.json" \
    --parameters "@${SCRIPTDIR}/parameters.json" \
    --parameters  "{ \"virtualNetworkId\": { \"value\": \"${VNET}\" } }" \
    --parameters  "{ \"subnetRef\": { \"value\": \"${SUBNET}\" } }" \
    --parameters  "{ \"adminPublicKey\": { \"value\": \"${PUBKEY}\" } }"
az deployment group wait --created --name "${DEPLOYMENT_NAME}" --resource-group "${RG}"
PUBIP=$(az vm list-ip-addresses  --resource-group "${RG}" --name "${VM_NAME}" --query "[].virtualMachine.network.publicIpAddresses[0].ipAddress" --output tsv)
echo "Jump host created. Cleanup by deleteing the resource group."
echo "Connect to the jump host with the following command:"
echo -e "ssh azureuser@${PUBIP}\n"
echo "Expose any nodes's debugd port locally:"
echo -e "NODEIP=<IP OF CONSTELLATION NODE> && \n\
    ssh -M -S debugd -fNT -L \"4000:\${NODEIP}:4000\" azureuser@${PUBIP} && \n\
    ./cdbg deploy --ips localhost && \n\
    ssh -S debugd -O exit azureuser@${PUBIP}\n"
echo "Connect to any constellation node using the following command:"
echo "ssh -J azureuser@${PUBIP} <USER>@<IP OF CONSTELLATION NODE>"
