#!/bin/bash

# List All Builds Script
# This script lists all available build tags with details

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

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

echo -e "${BLUE}=== Available Builds ===${NC}"
echo ""

# Check if Git is initialized
if [ ! -d ".git" ]; then
    echo -e "${YELLOW}Git repository not initialized.${NC}"
    echo -e "${YELLOW}Run build-with-backup.sh first to initialize Git.${NC}"
    exit 1
fi

# Get current commit
CURRENT_COMMIT=$(git rev-parse --short HEAD)
CURRENT_TAG=$(git describe --tags --exact-match 2>/dev/null || echo "No tag")

echo -e "${GREEN}Current commit: ${CURRENT_COMMIT}${NC}"
if [ "$CURRENT_TAG" != "No tag" ]; then
    echo -e "${GREEN}Current tag: ${CURRENT_TAG}${NC}"
fi
echo ""

# List all build tags with details
BUILD_TAGS=$(git tag -l "build-*" | sort -V -r)

if [ -z "$BUILD_TAGS" ]; then
    echo -e "${YELLOW}No build tags found.${NC}"
    echo -e "${YELLOW}Run build-with-backup.sh to create your first build.${NC}"
    exit 0
fi

echo -e "${BLUE}Build History:${NC}"
echo ""

COUNT=0
for TAG in $BUILD_TAGS; do
    COUNT=$((COUNT + 1))
    COMMIT=$(git rev-parse --short "$TAG")
    DATE=$(git log -1 --format=%ai "$TAG")
    MESSAGE=$(git log -1 --format=%s "$TAG")
    
    # Check if this is the current commit
    if [ "$COMMIT" = "$CURRENT_COMMIT" ]; then
        echo -e "${GREEN}[$COUNT] ${TAG} ${NC}(Current)"
    else
        echo -e "[$COUNT] ${TAG}"
    fi
    echo -e "    Commit: ${COMMIT}"
    echo -e "    Date: ${DATE}"
    echo -e "    Message: ${MESSAGE}"
    echo ""
done

echo -e "${YELLOW}Total builds: ${COUNT}${NC}"
echo ""
echo -e "${YELLOW}To restore a build, run:${NC}"
echo -e "${YELLOW}  ./restore-build.sh <build-tag>${NC}"
