#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${ROOT_DIR}/.env.docker.production"
COMPOSE_FILE="${ROOT_DIR}/docker-compose.registry.local.yml"
AUTH_DIR="${ROOT_DIR}/docker/registry/auth"
AUTH_FILE="${AUTH_DIR}/htpasswd"

read_env_value() {
  local key="$1"
  local line

  line="$(grep -E "^${key}=" "${ENV_FILE}" | tail -n 1 || true)"
  line="${line#*=}"

  if [[ "${line}" == \"*\" && "${line}" == *\" ]]; then
    line="${line:1:-1}"
  elif [[ "${line}" == \'*\' && "${line}" == *\' ]]; then
    line="${line:1:-1}"
  fi

  printf '%s' "${line}"
}

if [[ ! -f "${ENV_FILE}" ]]; then
  echo "Missing ${ENV_FILE}" >&2
  exit 1
fi

mkdir -p "${AUTH_DIR}"

REGISTRY_USER_VALUE="$(read_env_value REGISTRY_USER)"
REGISTRY_PASSWORD_VALUE="$(read_env_value REGISTRY_PASSWORD)"

if [[ -n "${REGISTRY_USER_VALUE}" && -n "${REGISTRY_PASSWORD_VALUE}" ]]; then
  docker run --rm --entrypoint htpasswd httpd:2-alpine -Bbn "${REGISTRY_USER_VALUE}" "${REGISTRY_PASSWORD_VALUE}" > "${AUTH_FILE}"
  chmod 600 "${AUTH_FILE}"
elif [[ ! -f "${AUTH_FILE}" ]]; then
  echo "Set REGISTRY_USER and REGISTRY_PASSWORD in ${ENV_FILE} or create ${AUTH_FILE} manually." >&2
  exit 1
fi

docker compose -p rentaldrivego-registry-local --env-file "${ENV_FILE}" -f "${COMPOSE_FILE}" up -d

echo "Local registry is starting on port 5000."
