#!/bin/bash

# Build with Automatic Git Backup Script
# This script automatically commits changes and creates a build tag before building

set -e  # Exit on error

PROJECT_DIR="/var/www/html/erp_codearya"
cd "$PROJECT_DIR"

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== Build with Automatic Git Backup ===${NC}"

# Check if Git is initialized
if [ ! -d ".git" ]; then
    echo -e "${YELLOW}Git not initialized. Initializing Git repository...${NC}"
    git init
    git config user.name "ERP System"
    git config user.email "system@codearya.com"
    echo -e "${GREEN}Git repository initialized.${NC}"
fi

# Check if there are any changes to commit
if [ -z "$(git status --porcelain)" ]; then
    echo -e "${YELLOW}No changes to commit.${NC}"
else
    echo -e "${GREEN}Staging all changes...${NC}"
    git add -A
    
    # Create commit message with timestamp
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    COMMIT_MSG="Auto-backup before build - $TIMESTAMP"
    
    echo -e "${GREEN}Committing changes...${NC}"
    git commit -m "$COMMIT_MSG" || {
        echo -e "${YELLOW}Nothing to commit or commit failed. Continuing...${NC}"
    }
fi

# Generate build tag
BUILD_NUMBER=$(git tag -l "build-*" | wc -l | tr -d ' ')
BUILD_NUMBER=$((BUILD_NUMBER + 1))
BUILD_TAG="build-v${BUILD_NUMBER}-$(date '+%Y%m%d-%H%M%S')"

echo -e "${GREEN}Creating build tag: ${BUILD_TAG}${NC}"
if git tag -a "$BUILD_TAG" -m "Build backup - $TIMESTAMP" 2>/dev/null; then
    echo -e "${GREEN}Build tag created successfully: ${BUILD_TAG}${NC}"
else
    echo -e "${YELLOW}Tag creation failed or tag already exists. Trying with timestamp...${NC}"
    BUILD_TAG="build-v${BUILD_NUMBER}-$(date '+%Y%m%d-%H%M%S')"
    git tag -a "$BUILD_TAG" -m "Build backup - $TIMESTAMP"
fi

# Get current commit hash
CURRENT_COMMIT=$(git rev-parse --short HEAD)
echo -e "${GREEN}Current commit: ${CURRENT_COMMIT}${NC}"
echo -e "${GREEN}Build tag created: ${BUILD_TAG}${NC}"

# Build Backend
echo -e "${GREEN}Building backend...${NC}"
cd backend
cargo build --release || {
    echo -e "${RED}Backend build failed!${NC}"
    exit 1
}
cd ..

# Build Frontend (if needed)
if [ -d "frontend" ] && [ -f "frontend/package.json" ]; then
    echo -e "${GREEN}Building frontend...${NC}"
    cd frontend
    npm run build || {
        echo -e "${YELLOW}Frontend build failed or not configured.${NC}"
    }
    cd ..
fi

# Create a build info file
BUILD_INFO_FILE=".build-info"
cat > "$BUILD_INFO_FILE" << EOF
BUILD_TAG=$BUILD_TAG
BUILD_DATE=$(date '+%Y-%m-%d %H:%M:%S')
COMMIT_HASH=$CURRENT_COMMIT
BUILD_NUMBER=$BUILD_NUMBER
EOF

echo -e "${GREEN}Build info saved to ${BUILD_INFO_FILE}${NC}"

# Optional: Commit build artifacts (uncomment if you want to track builds)
# git add "$BUILD_INFO_FILE"
# git commit -m "Build artifacts for $BUILD_TAG" || true

# Push to remote backup (GitHub) if configured
if git remote | grep -q origin; then
    echo -e "${GREEN}Pushing to GitHub cloud backup...${NC}"
    if git push origin master --tags 2>/dev/null; then
        echo -e "${GREEN}✅ Backed up to GitHub successfully!${NC}"
    else
        echo -e "${YELLOW}⚠️  GitHub push failed. Local backup still available.${NC}"
        echo -e "${YELLOW}   You can push manually later with: git push origin master --tags${NC}"
    fi
fi

echo -e "${GREEN}=== Build completed successfully! ===${NC}"
echo -e "${GREEN}Build Tag: ${BUILD_TAG}${NC}"
echo -e "${GREEN}Commit: ${CURRENT_COMMIT}${NC}"
echo -e "${YELLOW}To restore this build, run: ./restore-build.sh ${BUILD_TAG}${NC}"
