name: Local Docker Build (Main)

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  build:
    runs-on: host
    
    steps:
    - name: Checkout code
      run: |
        echo "Current workspace: $(pwd)"
        
        # Clean workspace and temp directory first
        rm -rf * .git* 2>/dev/null || true
        rm -rf /tmp/repo 2>/dev/null || true
        
        # Clone the repository since Gitea runner doesn't auto-checkout
        echo "Cloning repository..."
        git clone --branch main http://${{ secrets.username }}:${{ secrets.token }}@192.168.253.221:3000/sbcrumb/nfoguard.git /tmp/repo
        cp -r /tmp/repo/* .
        cp -r /tmp/repo/.* . 2>/dev/null || true
        rm -rf /tmp/repo
        
        echo "Repository cloned successfully"
        ls -la
        echo "Checking Dockerfile:"
        head -30 Dockerfile

    - name: Check Docker availability
      run: |
        echo "Checking Docker installation..."
        which docker || (echo "Docker not found in PATH" && exit 1)
        docker --version || (echo "Docker not available" && exit 1)
        docker info || (echo "Docker daemon not running" && exit 1)

    - name: Configure Docker for local registry
      run: |
        echo "Configuring Docker client for insecure local registry..."
        LOCAL_REGISTRY="192.168.253.221:3000"
        
        # We can't use sudo in the container, so we'll configure the client differently
        export DOCKER_CONFIG=/tmp/docker-config
        mkdir -p $DOCKER_CONFIG
        
        # Create Docker client config for insecure registry
        cat > $DOCKER_CONFIG/config.json << EOF
        {
          "auths": {},
          "HttpHeaders": {
            "User-Agent": "Docker-Client/20.10.0 (linux)"
          },
          "credsStore": "",
          "credHelpers": {},
          "experimental": "disabled"
        }
        EOF
        
        echo "Docker client config created"
        echo "Note: Since we can't modify daemon config in container, we'll use --insecure-registry flag"
        
        echo "Testing registry connectivity..."
        curl -s "http://$LOCAL_REGISTRY/v2/" && echo "✅ Registry accessible via HTTP" || echo "❌ Registry not accessible"

    - name: Build Docker image with caching
      run: |
        echo "Building Docker image with layer caching..."
        LOCAL_REGISTRY="192.168.253.221:3000"
        CACHE_IMAGE="$LOCAL_REGISTRY/sbcrumb/nfoguard:buildcache"
        
        # Clear any existing Docker configs to prevent permission issues
        unset DOCKER_CONFIG
        export HOME=/tmp/docker-home
        mkdir -p $HOME
        
        # Enable Docker BuildKit for better caching
        export DOCKER_BUILDKIT=1
        
        # Check if cache image exists and pull it
        echo "Checking for existing cache image..."
        CACHE_ARGS=""
        if curl -s "http://$LOCAL_REGISTRY/v2/sbcrumb/nfoguard/manifests/buildcache" > /dev/null 2>&1; then
          echo "✅ Cache manifest found, pulling image..."
          if docker pull "$CACHE_IMAGE" 2>/dev/null; then
            echo "✅ Cache image pulled successfully"
            CACHE_ARGS="--cache-from=$CACHE_IMAGE"
          else
            echo "⚠️ Cache manifest exists but pull failed"
          fi
        else
          echo "ℹ️ No cache image found (first build or cache expired)"
        fi
        
        # Build with cache (if available)
        echo "Building with layer caching..."
        VERSION=$(cat VERSION 2>/dev/null || echo "unknown")
        echo "Building version: $VERSION"
        
        docker build \
          $CACHE_ARGS \
          --build-arg GIT_BRANCH=main \
          --build-arg BUILD_SOURCE=gitea \
          --tag nfoguard:latest \
          --tag nfoguard:${VERSION}-gitea \
          --tag nfoguard:${{ github.sha }} \
          --tag "$CACHE_IMAGE" \
          .
        
        echo "Docker image built and tagged successfully"
        
        # Show layer info for debugging (with error handling)
        echo "=== Image layer history ==="
        if docker history nfoguard:latest --format "table {{.CreatedBy}}\t{{.Size}}" 2>/dev/null; then
          echo "✅ Image history displayed successfully"
        else
          echo "⚠️ Could not display image history (permissions issue, but build succeeded)"
        fi

    - name: Login and Push to Gitea registry (local IP only)
      continue-on-error: true  # Don't fail the build if local registry fails
      run: |
        echo "Using LOCAL IP ONLY - no Cloudflare tunnel!"
        export DOCKER_CONFIG=/tmp/docker-config
        
        # Force local IP - never use domain
        LOCAL_REGISTRY="192.168.253.221:3000"
        echo "Registry: $LOCAL_REGISTRY (LOCAL IP ONLY)"
        
        # Check image size
        IMAGE_SIZE=$(docker images nfoguard:latest --format "table {{.Size}}" | tail -n1)
        echo "Image size: $IMAGE_SIZE"
        
        echo "Testing local registry connectivity..."
        curl -s "http://$LOCAL_REGISTRY/v2/" && echo "✅ Local registry accessible via HTTP" || echo "❌ Local registry not accessible"
        
        # Try multiple approaches to handle the HTTP issue
        echo "Attempting login to LOCAL registry..."
        
        # Approach 1: Try with explicit HTTP in auth
        if echo "${{ secrets.token }}" | docker --config $DOCKER_CONFIG login "$LOCAL_REGISTRY" -u "${{ secrets.username }}" --password-stdin 2>/dev/null; then
          echo "✅ Login succeeded with direct method"
          
          # Tag for local registry (cache image already tagged in build step)
          VERSION=$(cat VERSION 2>/dev/null || echo "unknown")
          docker tag nfoguard:latest "$LOCAL_REGISTRY/sbcrumb/nfoguard:latest"
          docker tag nfoguard:${VERSION}-gitea "$LOCAL_REGISTRY/sbcrumb/nfoguard:${VERSION}-gitea"
          docker tag nfoguard:latest "$LOCAL_REGISTRY/sbcrumb/nfoguard:${{ github.sha }}"
          
          echo "Pushing to LOCAL registry (gigabit speed!)..."
          
          # Push with reasonable timeout for local network
          echo "=== Pushing cache image (for faster future builds) ==="
          timeout 60 docker --config $DOCKER_CONFIG push "$LOCAL_REGISTRY/sbcrumb/nfoguard:buildcache" && echo "✅ Cache image pushed" || echo "⚠️ Cache push failed"
          
          echo "=== Pushing latest tag to LOCAL IP ==="
          if timeout 120 docker --config $DOCKER_CONFIG push "$LOCAL_REGISTRY/sbcrumb/nfoguard:latest"; then
            echo "✅ Latest tag pushed successfully to LOCAL registry"
            
            echo "=== Pushing version-gitea tag ==="
            if timeout 60 docker --config $DOCKER_CONFIG push "$LOCAL_REGISTRY/sbcrumb/nfoguard:${VERSION}-gitea"; then
              echo "✅ Version-gitea tag pushed successfully: ${VERSION}-gitea"
            fi
            
            echo "=== Pushing SHA tag to LOCAL IP ==="
            if timeout 60 docker --config $DOCKER_CONFIG push "$LOCAL_REGISTRY/sbcrumb/nfoguard:${{ github.sha }}"; then
              echo "✅ SHA tag pushed successfully to LOCAL registry"
            else
              echo "⚠️ SHA tag push failed but latest succeeded"
            fi
            
          else
            echo "❌ Push to LOCAL registry failed"
            echo "This is likely because Docker daemon needs insecure-registry configuration"
          fi
          
        else
          echo "❌ Local registry login failed"
          echo "This is expected - Docker daemon needs insecure-registry configuration"
          echo ""
          echo "🔧 To fix, run on the host machine:"
          echo "sudo mkdir -p /etc/docker"
          echo 'echo '"'"'{"insecure-registries":["'$LOCAL_REGISTRY'"]}'"'"' | sudo tee /etc/docker/daemon.json'
          echo "sudo systemctl restart docker"
          echo ""
          echo "⏭️ Continuing to Docker Hub push..."
        fi
        
        echo "🎉 Local registry step completed!"

        echo ""
        echo "🎉 Local build completed successfully!"
        echo ""
        VERSION=$(cat VERSION 2>/dev/null || echo "unknown")
        echo "📦 Available images:"
        echo "  Local Docker:   nfoguard:latest"
        echo "  Version tag:    nfoguard:${VERSION}-gitea"
        echo "  Local SHA:      nfoguard:${{ github.sha }}"
        echo "  Local Gitea:    192.168.253.221:3000/sbcrumb/nfoguard:latest"
        echo ""
        echo "🐳 Pull with: docker pull 192.168.253.221:3000/sbcrumb/nfoguard:${VERSION}-gitea"

  deploy:
    needs: build
    runs-on: host
    if: github.ref == 'refs/heads/main'
    
    steps:
    - name: Deploy application
      run: |
        echo "Deploying application..."
        # Add your deployment commands here
        # Examples:
        # docker-compose pull
        # docker-compose up -d
        # or
        # docker stop nfoguard || true
        # docker run -d --name nfoguard -p 8080:8080 nfoguard:latest
        echo "Deployment completed"