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

# build_and_push.sh <registry> <owner> <repo> [tag] [username] [token]
# Example:
#   ./scripts/build_and_push.sh git.templarz.com templarz wsmud latest tempalrz <TOKEN>

REGISTRY=${1:-}
OWNER=${2:-}
REPO=${3:-}
TAG=${4:-latest}
USERNAME=${5:-}
TOKEN=${6:-}

if [ -z "$REGISTRY" ] || [ -z "$OWNER" ] || [ -z "$REPO" ]; then
  echo "Usage: $0 <registry> <owner> <repo> [tag] [username] [token]"
  exit 1
fi

LOCAL_IMAGE="${REPO}:${TAG}"
REMOTE_IMAGE="${REGISTRY}/${OWNER}/${REPO}:${TAG}"

echo "Building image: $LOCAL_IMAGE"
docker build -t "$LOCAL_IMAGE" .

echo "Tagging image -> $REMOTE_IMAGE"
docker tag "$LOCAL_IMAGE" "$REMOTE_IMAGE"

if [ -n "$TOKEN" ]; then
  echo "Logging in to $REGISTRY using token (password-stdin)"
  echo "$TOKEN" | docker login "$REGISTRY" -u "${USERNAME:-$OWNER}" --password-stdin
else
  echo "Logging in to $REGISTRY interactively (you will be prompted)"
  docker login "$REGISTRY" -u "${USERNAME:-$OWNER}"
fi

echo "Pushing $REMOTE_IMAGE"
docker push "$REMOTE_IMAGE"

echo "Push finished: $REMOTE_IMAGE"
