#!/bin/sh
set -eu

if ! set -o pipefail 2>/dev/null; then
  :
fi

REPO_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
cd "${REPO_ROOT}"

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

if [ ! -f secrets/REGISTRY_USER ] || [ ! -f secrets/REGISTRY_PASSWORD ]; then
  echo "[remote-registry-login] missing registry credential files in secrets/" >&2
  exit 1
fi

REGISTRY_HOST="${REGISTRY_URL#http://}"
REGISTRY_HOST="${REGISTRY_HOST#https://}"
REGISTRY_USER="$(cat secrets/REGISTRY_USER)"
REGISTRY_PASSWORD="$(cat secrets/REGISTRY_PASSWORD)"

: "${REGISTRY_USER:?missing REGISTRY_USER}"
: "${REGISTRY_PASSWORD:?missing REGISTRY_PASSWORD}"

b64enc() {
  printf '%s' "$1" | base64 | tr -d '\n'
}

REGISTRY_HOST_B64="$(b64enc "${REGISTRY_HOST}")"
REGISTRY_USER_B64="$(b64enc "${REGISTRY_USER}")"
REGISTRY_PASSWORD_B64="$(b64enc "${REGISTRY_PASSWORD}")"
REMOTE_TARGET="${SSH_USER}@${SSH_HOST}"

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
"

ssh ${SSH_OPTS} "${REMOTE_TARGET}" \
  REGISTRY_HOST_B64="${REGISTRY_HOST_B64}" \
  REGISTRY_USER_B64="${REGISTRY_USER_B64}" \
  REGISTRY_PASSWORD_B64="${REGISTRY_PASSWORD_B64}" \
  sh -s <<'EOSSH'
set -eu

decode_b64() {
  printf '%s' "$1" | base64 -d
}

REGISTRY_HOST="$(decode_b64 "${REGISTRY_HOST_B64}")"
REGISTRY_USER="$(decode_b64 "${REGISTRY_USER_B64}")"
REGISTRY_PASSWORD="$(decode_b64 "${REGISTRY_PASSWORD_B64}")"

mkdir -p "${HOME}/.docker"
printf '%s' "${REGISTRY_PASSWORD}" | docker login "${REGISTRY_HOST}" -u "${REGISTRY_USER}" --password-stdin >/dev/null
echo "[remote-registry-login] logged into ${REGISTRY_HOST}"
EOSSH
