#!/bin/bash
################################################################################
# IGNY8 Application Packaging Script
# Creates a portable package containing only source code (no dependencies)
################################################################################

set -e

# Configuration
SOURCE_DIR="/data/app/igny8"
BACKUP_DIR="/data/backups/igny8"
DATE_STAMP=$(date +%Y%m%d_%H%M%S)
PACKAGE_NAME="igny8-app-${DATE_STAMP}.tar.gz"
TEMP_DIR="/tmp/igny8-package-${DATE_STAMP}"

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

echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}  IGNY8 Application Package Creator${NC}"
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo ""

# Create backup directory if it doesn't exist
mkdir -p "${BACKUP_DIR}"
echo -e "${YELLOW}📁 Backup directory: ${BACKUP_DIR}${NC}"

# Create temporary packaging directory
echo -e "${YELLOW}📦 Creating temporary package directory...${NC}"
mkdir -p "${TEMP_DIR}"

# Copy application files (excluding generated artifacts)
echo -e "${YELLOW}📋 Copying application source files...${NC}"
rsync -av \
    --exclude='.git' \
    --exclude='__pycache__' \
    --exclude='*.pyc' \
    --exclude='*.pyo' \
    --exclude='.pytest_cache' \
    --exclude='backend/.venv' \
    --exclude='backend/venv' \
    --exclude='backend/*.sql' \
    --exclude='backend/*.sqlite3' \
    --exclude='backend/celerybeat-schedule' \
    --exclude='backend/logs' \
    --exclude='backend/staticfiles' \
    --exclude='frontend/node_modules' \
    --exclude='frontend/dist' \
    --exclude='frontend/.vite' \
    --exclude='sites/node_modules' \
    --exclude='sites/dist' \
    --exclude='*.log' \
    --exclude='.DS_Store' \
    --exclude='Thumbs.db' \
    "${SOURCE_DIR}/" "${TEMP_DIR}/"

# Create package info file
echo -e "${YELLOW}📝 Creating package metadata...${NC}"
cat > "${TEMP_DIR}/PACKAGE_INFO.txt" << EOF
IGNY8 Application Package
=========================

Package Date: $(date '+%Y-%m-%d %H:%M:%S')
Package Name: ${PACKAGE_NAME}
Git Commit: $(cd ${SOURCE_DIR} && git rev-parse --short HEAD 2>/dev/null || echo "N/A")
Git Branch: $(cd ${SOURCE_DIR} && git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "N/A")

Contents:
- Backend Django application (igny8_core)
- Frontend React application (src)
- Docker configuration files
- Documentation

NOT Included (will be installed automatically):
- Python virtual environment (.venv)
- Node modules (node_modules)
- Build artifacts (dist)
- Database backups
- Log files
- Static files cache

Installation:
See INSTALLATION.md for complete setup instructions.
EOF

# Calculate package size
echo -e "${YELLOW}📊 Calculating package size...${NC}"
PACKAGE_SIZE=$(du -sh "${TEMP_DIR}" | cut -f1)
echo -e "${GREEN}   Package size: ${PACKAGE_SIZE}${NC}"

# Create compressed archive
echo -e "${YELLOW}🗜️  Creating compressed archive...${NC}"
cd "${TEMP_DIR}/.."
tar -czf "${BACKUP_DIR}/${PACKAGE_NAME}" "$(basename ${TEMP_DIR})"

# Cleanup temporary directory
echo -e "${YELLOW}🧹 Cleaning up temporary files...${NC}"
rm -rf "${TEMP_DIR}"

# Get final archive size
ARCHIVE_SIZE=$(du -sh "${BACKUP_DIR}/${PACKAGE_NAME}" | cut -f1)

# Calculate checksum
echo -e "${YELLOW}🔐 Calculating checksum...${NC}"
CHECKSUM=$(sha256sum "${BACKUP_DIR}/${PACKAGE_NAME}" | cut -d' ' -f1)

# Create checksum file
echo "${CHECKSUM}  ${PACKAGE_NAME}" > "${BACKUP_DIR}/${PACKAGE_NAME}.sha256"

# Summary
echo ""
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}✅ Package created successfully!${NC}"
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}Package: ${BACKUP_DIR}/${PACKAGE_NAME}${NC}"
echo -e "${GREEN}Size: ${ARCHIVE_SIZE}${NC}"
echo -e "${GREEN}SHA256: ${CHECKSUM}${NC}"
echo -e "${GREEN}Checksum file: ${BACKUP_DIR}/${PACKAGE_NAME}.sha256${NC}"
echo ""

# Cleanup old packages (keep last 7 days)
echo -e "${YELLOW}🗑️  Cleaning up packages older than 7 days...${NC}"
find "${BACKUP_DIR}" -name "igny8-app-*.tar.gz" -type f -mtime +7 -delete
find "${BACKUP_DIR}" -name "igny8-app-*.sha256" -type f -mtime +7 -delete

OLD_COUNT=$(find "${BACKUP_DIR}" -name "igny8-app-*.tar.gz" | wc -l)
echo -e "${GREEN}   Packages retained: ${OLD_COUNT}${NC}"

echo ""
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}✨ Backup complete!${NC}"
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"

exit 0
