#!/bin/bash
set -e

# Create a log directory for cron debugging
mkdir -p /app/logs
mkdir -p /app/app/logs

# Set proper permissions for log directories
touch /app/app/link_checker_daemon.log
chmod 666 /app/app/link_checker_daemon.log

# Log file for debugging
LOGFILE="/app/logs/cron_setup.log"
echo "=== Starting container $(date) ===" > $LOGFILE

# First run the setup script
./setup.sh >> $LOGFILE 2>&1

# Create a test script that will be executed by cron every minute
echo "#!/bin/bash
echo \"Cron job executed at \$(date)\" >> /app/logs/cron_test.log
" > /app/cron_test.sh

# Make it executable
chmod +x /app/cron_test.sh

# Create a permanent crontab file
echo "Creating permanent crontab file..." >> $LOGFILE
PERM_CRON_FILE="/app/crontab.txt"
echo "# MSD Broken Link Checker cron jobs" > $PERM_CRON_FILE
echo "* * * * * /app/cron_test.sh" >> $PERM_CRON_FILE
echo "0 5 * * 1,3,5 cd /app/app && python app_daemon.py --excel URLs.xlsx --max-retries 3 --retry-timeout-multiplier 2.0" >> $PERM_CRON_FILE
echo "30 5 * * 1,3,5 cd /app/app && python app_daemon.py --excel URLs_without_login.xlsx --without-login" >> $PERM_CRON_FILE

# Install crontab from the permanent file
echo "Installing crontab directly..." >> $LOGFILE
crontab $PERM_CRON_FILE

# Initialize cron service using all available methods
echo "Initializing cron service using multiple methods..." >> $LOGFILE

# Method 1: Directly using cron executable
echo "Method 1: Starting cron directly..." >> $LOGFILE
(cron -f >> $LOGFILE 2>&1) &

# Method 2: Using service command
echo "Method 2: Using service command..." >> $LOGFILE
service cron start >> $LOGFILE 2>&1 || echo "Service command failed" >> $LOGFILE

# Method 3: Using init.d script
echo "Method 3: Using init.d script..." >> $LOGFILE
if [ -f /etc/init.d/cron ]; then
    /etc/init.d/cron start >> $LOGFILE 2>&1 || echo "Init.d script failed" >> $LOGFILE
fi

# Verify crontab
echo "Current crontab configuration:" >> $LOGFILE
crontab -l >> $LOGFILE 2>&1 || echo "Unable to display crontab" >> $LOGFILE

# Create and start a standalone cron daemon
echo "Creating standalone cron daemon..." >> $LOGFILE
echo "#!/bin/bash
# This is a minimalist cron daemon that doesn't depend on the system cron
while true; do
  # Get current minute
  CURRENT_MIN=\$(date +%M)
  CURRENT_HOUR=\$(date +%H)
  CURRENT_DAY=\$(date +%d)
  CURRENT_MONTH=\$(date +%m)
  CURRENT_WEEKDAY=\$(date +%u)
  
  # Run the minute test script
  if [ -f /app/cron_test.sh ]; then
    echo \"[\$(date)] Running minute test script\" >> /app/logs/custom_cron.log
    /app/cron_test.sh
  fi
  
  # Check if it's time to run the main scripts (5:00 AM on Monday(1), Wednesday(3), Friday(5))
  if [ \"\$CURRENT_HOUR\" = \"05\" ] && [ \"\$CURRENT_MIN\" = \"00\" ] && ([ \"\$CURRENT_WEEKDAY\" = \"1\" ] || [ \"\$CURRENT_WEEKDAY\" = \"3\" ] || [ \"\$CURRENT_WEEKDAY\" = \"5\" ]); then
    echo \"[\$(date)] Running main script with URLs.xlsx\" >> /app/logs/custom_cron.log
    cd /app/app && python app_daemon.py --excel URLs.xlsx --max-retries 3 --retry-timeout-multiplier 2.0
  fi
  
  # Check if it's time to run the secondary script (5:30 AM on Monday(1), Wednesday(3), Friday(5))
  if [ \"\$CURRENT_HOUR\" = \"05\" ] && [ \"\$CURRENT_MIN\" = \"30\" ] && ([ \"\$CURRENT_WEEKDAY\" = \"1\" ] || [ \"\$CURRENT_WEEKDAY\" = \"3\" ] || [ \"\$CURRENT_WEEKDAY\" = \"5\" ]); then
    echo \"[\$(date)] Running script with URLs_without_login.xlsx\" >> /app/logs/custom_cron.log
    cd /app/app && python app_daemon.py --excel URLs_without_login.xlsx --without-login
  fi
  
  # Sleep until the next minute
  sleep 60
done
" > /app/custom_cron.sh
chmod +x /app/custom_cron.sh

# Start the custom cron daemon in the background
echo "Starting custom cron daemon..." >> $LOGFILE
/app/custom_cron.sh >> $LOGFILE 2>&1 &

# Create a cron watchdog script
echo "Creating cron watchdog script..." >> $LOGFILE
echo "#!/bin/bash
while true; do
  # Check if system cron is running
  if ! service cron status >/dev/null 2>&1; then
    echo \"[\$(date)] System cron not running, restarting...\" >> /app/logs/cron_watchdog.log
    service cron start
    sleep 3
  fi
  
  # Check if crontab is installed
  if ! crontab -l 2>/dev/null | grep -q \"MSD Broken Link Checker\"; then
    echo \"[\$(date)] Crontab not installed, reinstalling...\" >> /app/logs/cron_watchdog.log
    crontab /app/crontab.txt
  fi
  
  # Extra checks for log directories
  if [ ! -d \"/app/logs\" ]; then
    mkdir -p /app/logs
  fi
  
  if [ ! -d \"/app/app/logs\" ]; then
    mkdir -p /app/app/logs
  fi
  
  sleep 300
done
" > /app/cron_watchdog.sh
chmod +x /app/cron_watchdog.sh

# Start the cron watchdog in the background
echo "Starting cron watchdog daemon..." >> $LOGFILE
/app/cron_watchdog.sh >> $LOGFILE 2>&1 &

# Start HTTP server and explain what's happening
echo "Container startup complete. Multiple cron mechanisms have been started:" >> $LOGFILE
echo "1. System cron service" >> $LOGFILE
echo "2. Custom cron daemon (runs independently of system cron)" >> $LOGFILE
echo "3. Cron watchdog (monitors and restarts cron if needed)" >> $LOGFILE

echo "========================================================="
echo "MSD Broken Link Checker is now running."
echo "Check /app/logs/cron_test.log to verify cron is working."
echo "If cron isn't working, run ./check_cron.sh for diagnostics."
echo "========================================================="

# Keep the container running with a web server
exec python -m http.server ${PORT:-8080} 