#!/usr/bin/env bash
set -euo pipefail
[[ "${DEBUG_DEPLOY:-0}" = "1" ]] && set -x
trap 'echo "[bootstrap-shared-network] error at line $LINENO" >&2' ERR

: "${SSH_USER:?missing SSH_USER}"
: "${SSH_HOST:?missing SSH_HOST}"

REMOTE_TARGET="${SSH_USER}@${SSH_HOST}"
DOCKER_SHARED_NETWORK="${DOCKER_SHARED_NETWORK:-sendico-net}"

SSH_OPTS=(
  -i /root/.ssh/id_rsa
  -o StrictHostKeyChecking=no
  -o UserKnownHostsFile=/dev/null
  -o LogLevel=ERROR
  -o BatchMode=yes
  -o PreferredAuthentications=publickey
  -o ConnectTimeout=10
  -o ServerAliveInterval=5
  -o ServerAliveCountMax=2
)
if [[ "${DEBUG_DEPLOY:-0}" = "1" ]]; then
  SSH_OPTS+=(-vv)
fi

printf '[bootstrap-shared-network] target=%s network=%s\n' "$REMOTE_TARGET" "$DOCKER_SHARED_NETWORK" >&2

set +e
timeout 20s ssh "${SSH_OPTS[@]}" "$REMOTE_TARGET" \
  DOCKER_SHARED_NETWORK="$DOCKER_SHARED_NETWORK" bash -s <<'EOSSH'
set -euo pipefail
printf '[bootstrap-shared-network] connected user=%s\n' "$(whoami)" >&2
command -v docker >/dev/null 2>&1 || {
  echo "[bootstrap-shared-network] docker command not found on remote host" >&2
  exit 127
}
docker network inspect "$DOCKER_SHARED_NETWORK" >/dev/null 2>&1 || \
  docker network create "$DOCKER_SHARED_NETWORK"
EOSSH
ssh_status=$?
set -e

if [[ $ssh_status -ne 0 ]]; then
  if [[ $ssh_status -eq 124 ]]; then
    echo "[bootstrap-shared-network] timed out waiting for remote docker bootstrap" >&2
  fi
  exit "$ssh_status"
fi
