#!/bin/bash
set -e

docker_release() {
  local ghcr_username=""
  local repo_name=""
  local version_tag

  while true; do
    read -rp "Bitte Versionsnummer für das Docker-Image eingeben (z.B. v0.1): " version_tag
    if [[ -n "$version_tag" ]]; then
      break
    fi
    echo "Versionsnummer darf nicht leer sein."
  done

  local origin_url
  origin_url=$(git config --get remote.origin.url || true)
  if [[ -n "$origin_url" ]]; then
    local cleaned="${origin_url%.git}"
    if [[ "$cleaned" =~ github.com[:/]+([^/]+)/([^/]+)$ ]]; then
      ghcr_username="${BASH_REMATCH[1]}"
      repo_name="${BASH_REMATCH[2]}"
    fi
  fi

  ghcr_username="$(echo "${ghcr_username:-mboehmlaender}" | tr '[:upper:]' '[:lower:]')"
  repo_name="$(echo "${repo_name:-vault}" | tr '[:upper:]' '[:lower:]')"

  if [[ -z "$CR_PAT" ]]; then
    echo "CR_PAT (GitHub Token) nicht gesetzt! Bitte export CR_PAT=<token>"
    return 1
  fi

  echo "$CR_PAT" | docker login ghcr.io -u "$ghcr_username" --password-stdin

  docker build -t "ghcr.io/$ghcr_username/${repo_name}-backend:$version_tag" -f backend/Dockerfile backend
  docker tag "ghcr.io/$ghcr_username/${repo_name}-backend:$version_tag" "ghcr.io/$ghcr_username/${repo_name}-backend:latest"

  docker build -t "ghcr.io/$ghcr_username/${repo_name}-frontend:$version_tag" -f frontend/Dockerfile frontend
  docker tag "ghcr.io/$ghcr_username/${repo_name}-frontend:$version_tag" "ghcr.io/$ghcr_username/${repo_name}-frontend:latest"

  docker push "ghcr.io/$ghcr_username/${repo_name}-backend:$version_tag"
  docker push "ghcr.io/$ghcr_username/${repo_name}-backend:latest"
  docker push "ghcr.io/$ghcr_username/${repo_name}-frontend:$version_tag"
  docker push "ghcr.io/$ghcr_username/${repo_name}-frontend:latest"

  echo "Docker-Release $version_tag (backend/frontend) erfolgreich gebaut und zu GHCR gepusht!"
}

docker_release
