#!/bin/bash

# Comprehensive fix for git-integration service deployment failure
# Addresses permission issues and directory setup

set -e

echo "🚀 Fixing git-integration service deployment issues..."
echo "=================================================="

# Define paths
BASE_DIR="/home/ubuntu/codenuk-backend-live"
GIT_REPOS_DIR="$BASE_DIR/git-repos"
DIFFS_DIR="$GIT_REPOS_DIR/diffs"

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

# Step 2: Create and setup directories
echo "📁 Setting up git-repos directories..."
mkdir -p "$GIT_REPOS_DIR"
mkdir -p "$DIFFS_DIR"

# Step 3: Fix ownership and permissions
echo "👤 Fixing ownership and permissions..."
# UID 1001 matches the git-integration user in the container
sudo chown -R 1001:1001 "$GIT_REPOS_DIR"
chmod -R 755 "$GIT_REPOS_DIR"

# Step 4: Verify directory setup
echo "✅ Verifying directory setup..."
echo "Directory structure:"
ls -la "$GIT_REPOS_DIR"

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

echo "🚀 Starting git-integration service..."
docker compose up -d git-integration

# Step 6: Wait for service to start and check health
echo "⏳ Waiting for service to start..."
sleep 10

echo "🏥 Checking service health..."
docker compose ps git-integration

# Step 7: Check logs for any remaining issues
echo "📋 Recent service logs:"
docker compose logs --tail=20 git-integration

echo ""
echo "🎉 Git-integration service fix completed!"
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"
