#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${ENV_FILE:-${SCRIPT_DIR}/.env.docker.production}"

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

  if [[ ! -f "${ENV_FILE}" ]]; then
    return 0
  fi

  value="$(
    awk -F= -v key="$key" '
      /^[[:space:]]*#/ || index($0, "=") == 0 {
        next
      }
      {
        name = $1
        sub(/^[[:space:]]*export[[:space:]]+/, "", name)
        gsub(/^[[:space:]]+|[[:space:]]+$/, "", name)
        if (name == key) {
          value = substr($0, index($0, "=") + 1)
          gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)
        }
      }
      END {
        if (value != "") {
          print value
        }
      }
    ' "${ENV_FILE}"
  )"

  value="${value%$'\r'}"
  value="${value#\"}"
  value="${value%\"}"
  printf '%s' "${value}"
}

IMAGE_TAG="${IMAGE_TAG:-${1:-$(read_env_value IMAGE_TAG)}}"
IMAGE_TAG="${IMAGE_TAG:-latest}"
APP_IMAGE="${APP_IMAGE:-10.0.0.4/melabidi/carmanagement}"
REGISTRY_USER="${REGISTRY_USER:-melabidi}"
REGISTRY_TOKEN="${REGISTRY_TOKEN:-}"
VPN_CONTAINER="${VPN_CONTAINER:-}"
TRANSFER_DIR="${TRANSFER_DIR:-/opt/docker-image-transfer}"

usage() {
  cat <<'EOF'
Usage:
  VPN_CONTAINER=<container-id-or-name> ./fetch-image-through-vpn.sh [image-tag]

Optional env vars:
  APP_IMAGE       Default: 10.0.0.4/melabidi/carmanagement
  IMAGE_TAG       Default: IMAGE_TAG from .env.docker.production, otherwise latest
  REGISTRY_USER  Default: melabidi
  REGISTRY_TOKEN  Prompted when unset
  TRANSFER_DIR   Default: /opt/docker-image-transfer

The script uses skopeo inside the VPN container network and writes:
  ${TRANSFER_DIR}/carmanagement-${IMAGE_TAG}.tar
EOF
}

case "${1:-}" in
  -h|--help)
    usage
    exit 0
    ;;
esac

if [[ -z "${IMAGE_TAG}" ]]; then
  usage >&2
  exit 1
fi

if [[ -z "${VPN_CONTAINER}" ]]; then
  echo "VPN_CONTAINER is required." >&2
  usage >&2
  exit 1
fi

if ! command -v docker >/dev/null 2>&1; then
  echo "Missing required command: docker" >&2
  exit 1
fi

archive_name="carmanagement-${IMAGE_TAG}.tar"
archive_path="${TRANSFER_DIR}/${archive_name}"

sudo mkdir -p "${TRANSFER_DIR}"
sudo chmod 700 "${TRANSFER_DIR}"
sudo rm -f "${archive_path}"

if [[ -z "${REGISTRY_TOKEN}" ]]; then
  read -rsp "Registry token: " REGISTRY_TOKEN
  echo
fi

docker run --rm \
  --network "container:${VPN_CONTAINER}" \
  -v "${TRANSFER_DIR}:/transfer" \
  quay.io/skopeo/stable:latest \
  copy \
  --override-os linux \
  --override-arch amd64 \
  --src-tls-verify=false \
  --src-creds "${REGISTRY_USER}:${REGISTRY_TOKEN}" \
  "docker://${APP_IMAGE}:${IMAGE_TAG}" \
  "docker-archive:/transfer/${archive_name}:${APP_IMAGE}:${IMAGE_TAG}"

echo "Image archive ready: ${TRANSFER_DIR}/${archive_name}"
