#!/bin/bash
# Git post-receive hook for AutonetSellCar
# This hook is triggered when code is pushed to the bare repository
# It automatically deploys to staging environment

STAGING_DIR="/opt/autonet/staging"
GIT_DIR="/opt/autonet/git/autonet.git"
SCRIPTS_DIR="/opt/autonet/scripts"

echo ""
echo "========================================"
echo "  AutonetSellCar - Git Push Received"
echo "========================================"
echo ""

# Read the pushed ref
while read oldrev newrev refname; do
    branch=$(echo $refname | sed 's/refs\/heads\///')
    echo "Branch pushed: $branch"

    # Only deploy main branch
    if [ "$branch" = "main" ] || [ "$branch" = "master" ]; then
        echo "Deploying to staging..."
        echo ""

        # Checkout code to staging directory
        git --work-tree="$STAGING_DIR" --git-dir="$GIT_DIR" checkout -f "$branch"

        # Copy docker-compose files
        cp "$STAGING_DIR/docker-compose.staging.yml" "$STAGING_DIR/"
        cp "$STAGING_DIR/docker-compose.production.yml" "$STAGING_DIR/"

        # Run staging deployment script
        "$SCRIPTS_DIR/deploy-staging.sh"

        echo ""
        echo "========================================"
        echo "  Staging deployment complete!"
        echo "========================================"
        echo ""
        echo "  Test your changes at:"
        echo "  - Frontend: http://192.168.0.202:3001"
        echo "  - Backend:  http://192.168.0.202:8001/docs"
        echo ""
        echo "  When ready, run:"
        echo "  ssh server2 '/opt/autonet/scripts/deploy.sh promote'"
        echo ""
        echo "========================================"
    else
        echo "Skipping deployment for branch: $branch"
        echo "Only main/master branch triggers deployment"
    fi
done
