#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if PROJECT_ROOT="$(git -C "${SCRIPT_DIR}" rev-parse --show-toplevel 2>/dev/null)"; then
    :
else
    PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
fi
DOCKER_CONTEXT="${PROJECT_ROOT}"
DOCKERFILE_PATH="${PROJECT_ROOT}/Dockerfile"

REGISTRY_HOST="gitea.mindboost.team"
IMAGE_NAME="interkollektives/lichterei-web"
DEFAULT_TAG="0.0.2"

if ! command -v docker >/dev/null 2>&1; then
    echo "Docker is required but not found in PATH." >&2
    exit 1
fi

if ! docker buildx version >/dev/null 2>&1; then
    echo "Docker Buildx is required but not available. Please install/enable it in Docker Desktop or via the CLI plugin." >&2
    exit 1
fi

read -rp "Image tag [${DEFAULT_TAG}]: " INPUT_TAG
IMAGE_TAG="${INPUT_TAG:-$DEFAULT_TAG}"
IMAGE_REF="${REGISTRY_HOST}/${IMAGE_NAME}:${IMAGE_TAG}"

DEFAULT_PLATFORMS="linux/amd64"
read -rp "Target platforms [${DEFAULT_PLATFORMS}]: " INPUT_PLATFORMS
TARGET_PLATFORMS="${INPUT_PLATFORMS:-$DEFAULT_PLATFORMS}"

read -rp "Registry username: " REGISTRY_USER
read -rsp "Registry password or token: " REGISTRY_PASSWORD
echo

echo "Logging into ${REGISTRY_HOST} ..."
echo "${REGISTRY_PASSWORD}" | docker login "${REGISTRY_HOST}" \
    --username "${REGISTRY_USER}" \
    --password-stdin

cleanup() {
    docker logout "${REGISTRY_HOST}" >/dev/null 2>&1 || true
}
trap cleanup EXIT

echo "Bootstrapping buildx builder ..."
docker buildx inspect --bootstrap >/dev/null

echo "Building and pushing ${IMAGE_REF} for ${TARGET_PLATFORMS} ..."
docker buildx build \
    --platform "${TARGET_PLATFORMS}" \
    --file "${DOCKERFILE_PATH}" \
    --tag "${IMAGE_REF}" \
    --push \
    "${DOCKER_CONTEXT}"

echo "Image pushed successfully."
