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

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

usage() {
  cat <<EOF >&2
Usage: $(basename "$0") [tag] [service]

Arguments:
  tag        Image tag (if omitted, asked interactively), e.g. 200-develop
  service    Service name (default: web)

Environment variables:
  REGISTRY   Image registry  (default: ovh-docker.aectest.ir)
  PROJECT    Project namespace (default: tm)
  DOCKERFILE Path to Dockerfile (default: \$ROOT_DIR/Dockerfile)
  RUN_BUILD  Set to 1 to execute docker build (default: 0)
  PUSH       Set to 1 to docker push after build (default: 0)

Examples:
  $(basename "$0")
  $(basename "$0") 200-develop
  RUN_BUILD=1 $(basename "$0") 200-develop
  $(basename "$0") 200-develop web
  REGISTRY=ovh-docker.aectest.ir PROJECT=tm PUSH=1 $(basename "$0") 1.0.0 web
EOF
  exit 1
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
fi

TAG="${1:-}"
SERVICE="${2:-web}"
REGISTRY="${REGISTRY:-ovh-docker.aectest.ir}"
PROJECT="${PROJECT:-tm}"
DOCKERFILE="${DOCKERFILE:-$ROOT_DIR/Dockerfile}"
RUN_BUILD="${RUN_BUILD:-0}"
PUSH="${PUSH:-0}"

if [[ -z "$TAG" ]]; then
  read -r -p "Enter image tag (example: 200-develop): " TAG
fi

if [[ -z "$TAG" ]]; then
  echo "Tag is required." >&2
  exit 1
fi

if [[ "$DOCKERFILE" != /* ]]; then
  DOCKERFILE="$ROOT_DIR/$DOCKERFILE"
fi

if [[ ! -f "$DOCKERFILE" ]]; then
  echo "Dockerfile not found at $DOCKERFILE" >&2
  exit 1
fi

IMAGE="$REGISTRY/$PROJECT/$SERVICE:$TAG"

echo "Prepared image: $IMAGE"
echo "  context:    $ROOT_DIR"
echo "  dockerfile: $DOCKERFILE"
echo "  command:    docker build -t $IMAGE -f $DOCKERFILE $ROOT_DIR"
echo

if [[ "$RUN_BUILD" != "1" ]]; then
  echo "Manual mode: build command is shown only."
  echo "Run with RUN_BUILD=1 to execute the build."
  exit 0
fi

docker build -t "$IMAGE" -f "$DOCKERFILE" "$ROOT_DIR"

echo
echo "Build complete: $IMAGE"

if [[ "$PUSH" == "1" ]]; then
  echo "Pushing $IMAGE"
  docker push "$IMAGE"
  echo "Push complete: $IMAGE"
fi
