#!/bin/bash

# SQDC Dashboard Deployment Script
# Usage: ./scripts/deploy.sh [registry_url] [registry_user] [registry_password] [repository_path]

set -e

REGISTRY_URL=${1:-"gitea.vidoks.fr"}
REGISTRY_USER=${2}
REGISTRY_PASSWORD=${3}
REPOSITORY_PATH=${4:-"sortifal/pfee"}
NAMESPACE="sqdc-dashboard"

echo "🚀 Deploying SQDC Dashboard..."

# Check if registry credentials are provided
if [ -z "$REGISTRY_USER" ] || [ -z "$REGISTRY_PASSWORD" ]; then
  echo "⚠️  Warning: Registry credentials not provided. Using local image."
  REGISTRY_URL="local"
fi

# Build Docker image
echo "📦 Building Docker image..."
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

if [ "$REGISTRY_URL" != "local" ]; then
  # Login to registry
  echo "🔐 Logging in to registry..."
  echo "$REGISTRY_PASSWORD" | docker login $REGISTRY_URL -u $REGISTRY_USER --password-stdin

  # Build and push to registry
  IMAGE_NAME="$REGISTRY_URL/$REPOSITORY_PATH"
  docker build -t $IMAGE_NAME:$TIMESTAMP .
  docker tag $IMAGE_NAME:$TIMESTAMP $IMAGE_NAME:latest
  docker push $IMAGE_NAME:$TIMESTAMP
  docker push $IMAGE_NAME:latest
  echo "✅ Docker image pushed: $IMAGE_NAME:$TIMESTAMP"
else
  # Build local image
  docker build -t sqdc-dashboard:latest .
  docker tag sqdc-dashboard:latest sqdc-dashboard:$TIMESTAMP
  echo "✅ Docker image built: sqdc-dashboard:$TIMESTAMP"
fi

# Apply Kubernetes manifests
echo "☸️  Applying Kubernetes manifests..."
kubectl apply -f k8s/namespace.yaml

# Create registry secret if credentials provided
if [ "$REGISTRY_URL" != "local" ]; then
  echo "🔑 Creating registry credentials secret..."
  kubectl create secret docker-registry registry-credentials \
    --docker-server=$REGISTRY_URL \
    --docker-username=$REGISTRY_USER \
    --docker-password=$REGISTRY_PASSWORD \
    -n $NAMESPACE \
    --dry-run=client -o yaml | kubectl apply -f -
fi

kubectl apply -f k8s/deployment.yaml
kubectl apply -f k8s/service.yaml
kubectl apply -f k8s/ingress.yaml

# Wait for rollout
echo "⏳ Waiting for deployment to complete..."
kubectl rollout status deployment/sqdc-dashboard -n $NAMESPACE --timeout=5m

# Display deployment info
echo ""
echo "📊 Deployment Status:"
kubectl get pods -n $NAMESPACE
echo ""
kubectl get svc -n $NAMESPACE
echo ""
kubectl get ingress -n $NAMESPACE

echo ""
echo "✅ Deployment complete!"
echo "🌐 Access the dashboard at: http://sqdc-dashboard.local"
