#!/bin/bash
# Refresh NextGen App by pulling latest code and restarting pods

BRANCH=$1

if [[ "$BRANCH" != "main" && "$BRANCH" != "dev" ]]; then
    echo "Usage: $0 [main|dev]"
    exit 1
fi

APP_DIR="/root/geocrop/apps/nextgen-$BRANCH"
DEPLOYMENT="next-gen-$BRANCH"

echo "=== Refreshing NextGen $BRANCH ==="

cd "$APP_DIR" || { echo "Directory $APP_DIR not found"; exit 1; }

echo "Pulling latest code..."
git pull origin "$BRANCH"

# Re-apply static serving patch if missing
INDEX_JS="server/src/index.js"
if ! grep -q "client/dist" "$INDEX_JS"; then
    echo "Re-applying static serving patch to $INDEX_JS..."
    sed -i '/\/\/ Start server/i \/\/ Serve static frontend files in production\napp.use(express.static(path.join(__dirname, "../../client/dist")));\napp.get("*", (req, res) => {\n  res.sendFile(path.join(__dirname, "../../client/dist/index.html"));\n});\n' "$INDEX_JS"
fi

echo "Installing server dependencies..."
cd server && npm install --production && cd ..

echo "Building client..."
cd client && npm install --include=dev && npm run build && cd ..

echo "Restarting Kubernetes deployment..."
kubectl rollout restart deployment "$DEPLOYMENT" -n nextgen

echo "Done! Monitoring rollout..."
kubectl rollout status deployment "$DEPLOYMENT" -n nextgen
