#!/bin/bash
# Reboot Recovery Test Script for DailyNotification Plugin
# Usage: ./reboot-test.sh

set -e

# Configuration
APP_PACKAGE="org.timesafari.dailynotification"
APP_ACTIVITY=".MainActivity"
BOOT_WAIT_TIME=60  # Wait 60 seconds for boot completion
RECOVERY_TIMEOUT=30  # Wait 30 seconds for recovery

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

# Function to print colored output
print_status() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# Function to wait for device to be ready
wait_for_device() {
    print_status $YELLOW "⏳ Waiting for device to be ready..."
    adb wait-for-device
    sleep 5
    
    # Wait for boot completion
    local boot_completed=false
    local attempts=0
    local max_attempts=12  # 60 seconds total
    
    while [ $attempts -lt $max_attempts ]; do
        if adb shell getprop sys.boot_completed 2>/dev/null | grep -q "1"; then
            boot_completed=true
            break
        fi
        print_status $YELLOW "   Boot not complete, waiting... ($((attempts + 1))/$max_attempts)"
        sleep 5
        attempts=$((attempts + 1))
    done
    
    if [ "$boot_completed" = true ]; then
        print_status $GREEN "✅ Device boot completed"
        sleep 5  # Additional wait for services to start
    else
        print_status $RED "❌ Device boot timeout"
        exit 1
    fi
}

# Function to schedule notification (manual step)
schedule_notification() {
    print_status $BLUE "📅 Scheduling test notification..."
    adb shell am start -n $APP_PACKAGE/$APP_ACTIVITY
    sleep 3
    
    print_status $YELLOW "⚠️  Manual step: Schedule notification in app"
    print_status $YELLOW "   - Tap 'Test Notification' button"
    print_status $YELLOW "   - Wait for 'Notification scheduled for [time]!' message"
    print_status $YELLOW "   - Note the scheduled time (5 minutes from now)"
    read -p "Press Enter when notification is scheduled..."
}

# Function to check recovery logs
check_recovery_logs() {
    print_status $BLUE "🔍 Checking recovery logs..."
    
    # Check for boot receiver activation
    if adb logcat -d | grep -q "Device boot completed - restoring notifications"; then
        print_status $GREEN "✅ Boot receiver activated"
    else
        print_status $RED "❌ Boot receiver not activated"
        return 1
    fi
    
    # Check for recovery completion
    if adb logcat -d | grep -q "Notification recovery completed successfully"; then
        print_status $GREEN "✅ Recovery completed successfully"
        return 0
    else
        print_status $RED "❌ Recovery not completed"
        return 1
    fi
}

# Function to check scheduled alarms
check_scheduled_alarms() {
    print_status $BLUE "⏰ Checking scheduled alarms..."
    
    local alarm_output=$(adb shell "dumpsys alarm | grep timesafari" 2>/dev/null || true)
    
    if [ -n "$alarm_output" ]; then
        print_status $GREEN "✅ Alarms found:"
        echo "$alarm_output"
        return 0
    else
        print_status $RED "❌ No alarms found"
        return 1
    fi
}

# Function to check boot receiver registration
check_boot_receiver() {
    print_status $BLUE "🔧 Checking boot receiver registration..."
    
    local receiver_output=$(adb shell "dumpsys package $APP_PACKAGE | grep -A10 -B10 receiver" 2>/dev/null || true)
    
    if echo "$receiver_output" | grep -q "BootReceiver"; then
        print_status $GREEN "✅ Boot receiver registered"
        return 0
    else
        print_status $RED "❌ Boot receiver not registered"
        return 1
    fi
}

# Function to reboot device
reboot_device() {
    print_status $BLUE "🔄 Rebooting device..."
    print_status $YELLOW "   This will take about 2-3 minutes..."
    
    adb reboot
    wait_for_device
}

# Function to run ADB command and check result
run_adb_command() {
    local command=$1
    local description=$2
    
    print_status $BLUE "🔧 $description"
    if adb $command; then
        print_status $GREEN "✅ $description - Success"
        return 0
    else
        print_status $RED "❌ $description - Failed"
        return 1
    fi
}

# Main test function
main() {
    print_status $BLUE "🔄 Starting Reboot Recovery Test"
    print_status $BLUE "================================"
    
    # Check ADB connection
    if ! adb devices | grep -q "device$"; then
        print_status $RED "❌ No Android device connected via ADB"
        exit 1
    fi
    
    print_status $GREEN "✅ ADB device connected"
    
    # Pre-reboot checks
    print_status $BLUE "🔍 Pre-reboot checks..."
    
    # Check boot receiver registration
    if ! check_boot_receiver; then
        print_status $RED "❌ Boot receiver not properly registered"
        exit 1
    fi
    
    # Schedule notification
    schedule_notification
    
    # Verify initial scheduling
    print_status $BLUE "📋 Verifying initial scheduling..."
    if check_scheduled_alarms; then
        print_status $GREEN "✅ Initial scheduling successful"
    else
        print_status $RED "❌ Initial scheduling failed"
        exit 1
    fi
    
    # Reboot device
    reboot_device
    
    # Post-reboot checks
    print_status $BLUE "🔍 Post-reboot checks..."
    
    # Check recovery logs
    if check_recovery_logs; then
        print_status $GREEN "✅ Recovery successful"
    else
        print_status $RED "❌ Recovery failed"
        exit 1
    fi
    
    # Verify alarms restored
    if check_scheduled_alarms; then
        print_status $GREEN "✅ Alarms restored successfully"
    else
        print_status $RED "❌ Alarms not restored"
        exit 1
    fi
    
    # Final status
    print_status $GREEN "🎉 Reboot recovery test completed successfully!"
    print_status $BLUE "⏰ Wait for the scheduled notification to appear (5 minutes from original schedule)"
    print_status $YELLOW "👀 Monitor notification panel for the test notification"
}

# Help function
show_help() {
    echo "Reboot Recovery Test Script"
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -h, --help     Show this help message"
    echo "  -v, --verbose  Enable verbose output"
    echo "  -w, --wait     Set boot wait time in seconds (default: 60)"
    echo ""
    echo "Examples:"
    echo "  $0                    # Run reboot test"
    echo "  $0 -w 90             # Run with 90 second boot wait"
    echo "  $0 -v                # Run with verbose output"
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -v|--verbose)
            set -x
            shift
            ;;
        -w|--wait)
            BOOT_WAIT_TIME="$2"
            shift 2
            ;;
        *)
            print_status $RED "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Run main function
main
