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

require_env() {
  local name="$1"
  if [[ -z "${!name:-}" ]]; then
    echo "Missing required environment variable: ${name}" >&2
    exit 1
  fi
}

require_env GITEA_REGISTRY
require_env GITEA_OWNER
require_env GITEA_IMAGE_NAME
require_env GITEA_USERNAME
require_env GITEA_TOKEN

GITEA_IMAGE_TAG="${GITEA_IMAGE_TAG:-latest}"
IMAGE_REF="${GITEA_REGISTRY}/${GITEA_OWNER}/${GITEA_IMAGE_NAME}:${GITEA_IMAGE_TAG}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERVER_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"

docker build -t "${IMAGE_REF}" "${SERVER_DIR}"
printf '%s' "${GITEA_TOKEN}" | docker login "${GITEA_REGISTRY}" \
  --username "${GITEA_USERNAME}" \
  --password-stdin
docker push "${IMAGE_REF}"

echo "Pushed ${IMAGE_REF}"
