#!/usr/bin/env bash
set -euo pipefail

BASE_IMAGE="${BASE_IMAGE:-mirror.gcr.io/library/debian:bookworm-slim}"
RUNTIME_BASE_IMAGE="${RUNTIME_BASE_IMAGE:-vpn-proxy-runtime-base:bookworm-slim}"
SINGBOX_VERSION="${SINGBOX_VERSION:-1.12.13}"
APT_MIRROR="${APT_MIRROR:-http://mirror.yandex.ru/debian}"
APT_SECURITY_MIRROR="${APT_SECURITY_MIRROR:-http://mirror.yandex.ru/debian-security}"
HTTP_PROXY="${HTTP_PROXY:-$(docker info 2>/dev/null | awk -F': ' '/HTTP Proxy:/ {print $2; exit}')}"
HTTPS_PROXY="${HTTPS_PROXY:-$(docker info 2>/dev/null | awk -F': ' '/HTTPS Proxy:/ {print $2; exit}')}"
NO_PROXY="${NO_PROXY:-$(docker info 2>/dev/null | awk -F': ' '/No Proxy:/ {print $2; exit}')}"

echo "Building runtime base: ${RUNTIME_BASE_IMAGE}"
echo "Source base image: ${BASE_IMAGE}"
echo "APT mirror: ${APT_MIRROR}"
echo "APT security mirror: ${APT_SECURITY_MIRROR}"
if [ -n "${HTTP_PROXY}" ]; then echo "HTTP proxy: ${HTTP_PROXY}"; fi
if [ -n "${HTTPS_PROXY}" ]; then echo "HTTPS proxy: ${HTTPS_PROXY}"; fi

docker build \
  --build-arg BASE_IMAGE="${BASE_IMAGE}" \
  --build-arg SINGBOX_VERSION="${SINGBOX_VERSION}" \
  --build-arg APT_MIRROR="${APT_MIRROR}" \
  --build-arg APT_SECURITY_MIRROR="${APT_SECURITY_MIRROR}" \
  --build-arg HTTP_PROXY="${HTTP_PROXY}" \
  --build-arg HTTPS_PROXY="${HTTPS_PROXY}" \
  --build-arg NO_PROXY="${NO_PROXY}" \
  --build-arg http_proxy="${HTTP_PROXY}" \
  --build-arg https_proxy="${HTTPS_PROXY}" \
  --build-arg no_proxy="${NO_PROXY}" \
  -f Dockerfile.runtime-base \
  -t "${RUNTIME_BASE_IMAGE}" \
  .
