#!/bin/bash

# Portfolio Snapshot Generation Cron Job
# This script should be added to crontab to run daily at 1:00 AM
# 
# To add to crontab:
# crontab -e
# Add line: 0 1 * * * /path/to/your/project/cron_portfolio_snapshots.sh
#
# Or for more frequent testing (every hour):
# 0 * * * * /path/to/your/project/cron_portfolio_snapshots.sh

# Set the project directory (update this path to your actual project directory)
PROJECT_DIR="/path/to/your/branch-system"

# Set the Python virtual environment path (if using virtual environment)
VENV_PATH="/path/to/your/venv"

# Log file for cron job output
LOG_FILE="$PROJECT_DIR/logs/portfolio_snapshots_cron.log"

# Create logs directory if it doesn't exist
mkdir -p "$PROJECT_DIR/logs"

# Function to log messages with timestamp
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Start logging
log_message "Starting portfolio snapshot generation cron job"

# Change to project directory
cd "$PROJECT_DIR" || {
    log_message "ERROR: Could not change to project directory: $PROJECT_DIR"
    exit 1
}

# Activate virtual environment if it exists
if [ -d "$VENV_PATH" ]; then
    source "$VENV_PATH/bin/activate" || {
        log_message "ERROR: Could not activate virtual environment: $VENV_PATH"
        exit 1
    }
    log_message "Activated virtual environment: $VENV_PATH"
fi

# Run the Django management command
log_message "Executing portfolio snapshot generation command"

python manage.py generate_portfolio_snapshots --verbose >> "$LOG_FILE" 2>&1

# Check the exit status
if [ $? -eq 0 ]; then
    log_message "Portfolio snapshot generation completed successfully"
else
    log_message "ERROR: Portfolio snapshot generation failed with exit code $?"
    
    # Optional: Send email notification on failure
    # echo "Portfolio snapshot generation failed at $(date)" | mail -s "Portfolio Snapshot Generation Failed" admin@yourcompany.com
fi

# Deactivate virtual environment if it was activated
if [ -d "$VENV_PATH" ]; then
    deactivate
    log_message "Deactivated virtual environment"
fi

log_message "Portfolio snapshot generation cron job completed"

# Optional: Clean up old log files (keep last 30 days)
find "$PROJECT_DIR/logs" -name "portfolio_snapshots_cron.log.*" -mtime +30 -delete 2>/dev/null

# Rotate log file if it gets too large (> 10MB)
if [ -f "$LOG_FILE" ] && [ $(stat -f%z "$LOG_FILE" 2>/dev/null || stat -c%s "$LOG_FILE" 2>/dev/null || echo 0) -gt 10485760 ]; then
    mv "$LOG_FILE" "$LOG_FILE.$(date +%Y%m%d_%H%M%S)"
    log_message "Log file rotated due to size"
fi