#!/bin/bash
set -e

# Blog Build & Deploy Script
REGISTRY="harbor.scottyah.com"
NAMESPACE="scottyah"
IMAGE_NAME="blog"
FULL_IMAGE="${REGISTRY}/${NAMESPACE}/${IMAGE_NAME}"

# Parse flags
BUILD_ONLY=false
DEPLOY_ONLY=false

while [[ $# -gt 0 ]]; do
  case $1 in
    --build-only)
      BUILD_ONLY=true
      shift
      ;;
    --deploy-only)
      DEPLOY_ONLY=true
      shift
      ;;
    -h|--help)
      echo "Usage: ./ship.sh [OPTIONS]"
      echo ""
      echo "Build and deploy Blog to Kubernetes"
      echo ""
      echo "Options:"
      echo "  --build-only    Only build and push Docker image"
      echo "  --deploy-only   Only deploy to Kubernetes (skip build)"
      echo "  -h, --help      Show this help message"
      echo ""
      echo "Examples:"
      echo "  ./ship.sh                  # Build and deploy"
      echo "  ./ship.sh --build-only     # Only build"
      echo "  ./ship.sh --deploy-only    # Only deploy"
      exit 0
      ;;
    *)
      echo "Unknown option: $1"
      echo "Use --help for usage information"
      exit 1
      ;;
  esac
done

# BUILD PHASE
if [ "$DEPLOY_ONLY" = false ]; then
  TIMESTAMP=$(date +%Y%m%d-%H%M%S)

  # Tags
  TAG_TIMESTAMP="${FULL_IMAGE}:${TIMESTAMP}"
  TAG_LATEST="${FULL_IMAGE}:latest"

  echo "🐦 Building Blog Docker image..."
  echo "Registry: ${REGISTRY}"
  echo "Image: ${FULL_IMAGE}"
  echo "Timestamp: ${TIMESTAMP}"
  echo ""

  # Build image
  echo "Building Docker image..."
  docker build \
    --network=host \
    -t "${TAG_TIMESTAMP}" \
    -t "${TAG_LATEST}" \
    "."

  echo ""
  echo "✅ Build complete!"
  echo ""
  echo "Tagged as:"
  echo "  - ${TAG_TIMESTAMP}"
  echo "  - ${TAG_LATEST}"
  echo ""

  # Push images
  echo "Pushing images to registry..."
  docker push "${TAG_TIMESTAMP}"
  docker push "${TAG_LATEST}"

  echo ""
  echo "🚀 Images pushed to Harbor registry!"
  echo ""
fi

# DEPLOY PHASE
if [ "$BUILD_ONLY" = false ]; then
  echo "🐦 Deploying Blog to Kubernetes..."
  echo ""

  # Apply Kubernetes configuration
  echo "Applying Kubernetes configuration..."
  kubectl apply -f "k8s.yaml"

  echo ""
  echo "Waiting for namespace to be ready..."
  kubectl wait --for=condition=Ready --timeout=10s namespace/blog 2>/dev/null || true

  echo ""
  echo "✅ Deployment complete!"
  echo ""
fi

if [ "$BUILD_ONLY" = false ] && [ "$DEPLOY_ONLY" = false ]; then
  echo "✨ Build and deployment complete!"
fi
