#!/bin/bash

# Server-side script to fix git-integration deployment issues
# Run this script on ubuntu@160.187.166.39

set -e

echo "🚀 Fixing git-integration service deployment on server..."
echo "============================================================"

# Get current directory
CURRENT_DIR=$(pwd)
echo "📍 Current directory: $CURRENT_DIR"

# Check if we're in the right directory
if [[ ! -f "docker-compose.yml" ]]; then
    echo "❌ Error: docker-compose.yml not found. Please run this script from the codenuk-backend-live directory."
    echo "Expected path: /home/ubuntu/codenuk-backend-live"
    exit 1
fi

echo "✅ Found docker-compose.yml - proceeding with fix..."

# Step 1: Stop the failing git-integration service
echo ""
echo "🛑 Step 1: Stopping git-integration service..."
docker compose stop git-integration 2>/dev/null || true
docker compose rm -f git-integration 2>/dev/null || true

# Step 2: Create the git-repos directory structure
echo ""
echo "📁 Step 2: Creating git-repos directory structure..."
mkdir -p git-repos
mkdir -p git-repos/diffs

# Step 3: Set proper ownership and permissions
echo ""
echo "👤 Step 3: Setting proper ownership and permissions..."
echo "Setting ownership to 1001:1001 (matches container user)..."
sudo chown -R 1001:1001 git-repos/
echo "Setting permissions to 755..."
chmod -R 755 git-repos/

# Step 4: Verify the directory setup
echo ""
echo "✅ Step 4: Verifying directory setup..."
echo "Directory listing:"
ls -la git-repos/
echo ""
echo "Permissions check:"
stat git-repos/
stat git-repos/diffs/

# Step 5: Rebuild the git-integration service
echo ""
echo "🔨 Step 5: Rebuilding git-integration service..."
docker compose build --no-cache git-integration

# Step 6: Start the git-integration service
echo ""
echo "🚀 Step 6: Starting git-integration service..."
docker compose up -d git-integration

# Step 7: Wait for service to start
echo ""
echo "⏳ Step 7: Waiting for service to start (30 seconds)..."
sleep 30

# Step 8: Check service status
echo ""
echo "🏥 Step 8: Checking service status..."
echo "Service status:"
docker compose ps git-integration

echo ""
echo "Service health check:"
docker compose exec git-integration curl -f http://localhost:8012/health 2>/dev/null || echo "Health check failed - service may still be starting"

# Step 9: Show recent logs
echo ""
echo "📋 Step 9: Recent service logs:"
docker compose logs --tail=30 git-integration

echo ""
echo "============================================================"
echo "🎉 Git-integration service fix completed!"
echo "============================================================"
echo ""
echo "✅ Directories created with proper permissions"
echo "✅ Service rebuilt and restarted"
echo ""
echo "If the service is still failing, check the logs with:"
echo "docker compose logs git-integration"
echo ""
echo "To check if the service is healthy:"
echo "curl http://localhost:8012/health"
