#!/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
  -q
)
if [[ "${DEBUG_DEPLOY:-0}" = "1" ]]; then
  SSH_OPTS=("${SSH_OPTS[@]/-q/}" -vv)
fi

ssh "${SSH_OPTS[@]}" "$REMOTE_TARGET" \
  DOCKER_SHARED_NETWORK="$DOCKER_SHARED_NETWORK" bash -s <<'EOSSH'
set -euo pipefail
docker network inspect "$DOCKER_SHARED_NETWORK" >/dev/null 2>&1 || \
  docker network create "$DOCKER_SHARED_NETWORK"
EOSSH
