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

# ── Configurable env vars ────────────────────────────────────────────
GF_REGISTRY_URL="${GF_REGISTRY_URL:-registry.gamefabric.io/your-org}"
GF_BRANCH="${GF_BRANCH:-development}"
GF_USERNAME="${GF_USERNAME:-your-service-account}"

IMAGE_NAME="samplegame-server"

# ── CLI params ───────────────────────────────────────────────────────
usage() {
    echo "Usage: $0 -p <password> -t <tag>"
    echo ""
    echo "  -p  Service-account password for the GameFabric container registry"
    echo "  -t  Tag for the built image (e.g. v1.0.0, build-1234)"
    exit 1
}

PASSWORD=""
TAG=""

while getopts ":p:t:" opt; do
    case ${opt} in
        p) PASSWORD="${OPTARG}" ;;
        t) TAG="${OPTARG}" ;;
        *) usage ;;
    esac
done

if [[ -z "${PASSWORD}" || -z "${TAG}" ]]; then
    usage
fi

REMOTE_IMAGE="${GF_REGISTRY_URL}/${GF_BRANCH}/${IMAGE_NAME}:${TAG}"

echo "==> Logging in to GameFabric registry at ${GF_REGISTRY_URL} ..."
echo "${PASSWORD}" | docker login -u "${GF_USERNAME}" --password-stdin "${GF_REGISTRY_URL}"

echo "==> Building image ${IMAGE_NAME}:${TAG} ..."
docker build --platform linux/amd64 -t "${IMAGE_NAME}:${TAG}" .

echo "==> Tagging as ${REMOTE_IMAGE} ..."
docker tag "${IMAGE_NAME}:${TAG}" "${REMOTE_IMAGE}"

echo "==> Pushing ${REMOTE_IMAGE} ..."
docker push --platform linux/amd64 "${REMOTE_IMAGE}"

echo "==> Done. Image available at ${REMOTE_IMAGE}"
