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

TARGET_GIT_URL="https://git.alphen.cloud/bramval/PsalmbordOnlineCE.git"
DOCKER_IMAGE="git.alphen.cloud/bramval/psalmbordonlinece"
BRANCH="main"

command -v git >/dev/null 2>&1 || { echo "git is not available in PATH" >&2; exit 1; }
command -v docker >/dev/null 2>&1 || { echo "docker is not available in PATH" >&2; exit 1; }

read -r -p "Enter version (e.g. 1.2.3): " version
version="${version//[[:space:]]/}"
if [[ -z "$version" ]]; then
  echo "Version cannot be empty" >&2
  exit 1
fi

# Basic docker tag safety
if [[ ! "$version" =~ ^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$ ]]; then
  echo "Invalid version '$version'. Use only letters/numbers and . _ - (max 128 chars)" >&2
  exit 1
fi

commit_message="Version ${version}"

current_branch="$(git branch --show-current)"
if [[ "$current_branch" != "$BRANCH" ]]; then
  echo "You are on branch '$current_branch' (expected '$BRANCH')." >&2
  read -r -p "Continue and push '$BRANCH' anyway? (y/N): " ans
  if [[ "${ans,,}" != "y" ]]; then
    echo "Aborted by user" >&2
    exit 1
  fi
fi

echo
echo "== Git: ensuring remote 'origin' points to ${TARGET_GIT_URL} =="
if git remote get-url origin >/dev/null 2>&1; then
  origin_url="$(git remote get-url origin)"
  if [[ "$origin_url" != "$TARGET_GIT_URL" ]]; then
    echo "Remote 'origin' is '$origin_url' -> updating to '$TARGET_GIT_URL'"
    git remote set-url origin "$TARGET_GIT_URL"
  fi
else
  echo "Remote 'origin' not found; adding it."
  git remote add origin "$TARGET_GIT_URL"
fi

echo
echo "== Git: status =="
git status -sb

read -r -p "Proceed with commit+push and docker push? (y/N): " confirm
if [[ "${confirm,,}" != "y" ]]; then
  echo "Aborted by user" >&2
  exit 1
fi

echo
echo "== Git: add/commit/push =="
git add -A

set +e
git commit -m "$commit_message"
commit_ec=$?
set -e
if [[ $commit_ec -ne 0 ]]; then
  echo "No changes to commit (or commit failed). Continuing to push anyway..." >&2
else
  echo "Committed: $commit_message"
fi

git push -u origin "$BRANCH"

echo
echo "== Docker: build/tag/push =="
echo "Docker image: $DOCKER_IMAGE"
echo "Tags: $version, latest"

docker build -t "${DOCKER_IMAGE}:${version}" -t "${DOCKER_IMAGE}:latest" .
docker push "${DOCKER_IMAGE}:${version}"
docker push "${DOCKER_IMAGE}:latest"

echo
echo "Done."
echo "If docker push failed due to auth, run: docker login git.alphen.cloud" >&2
