#!/bin/bash
# clean-android.sh
# Author: Matthew Raymer
# Date: 2025-08-19
# Description: Clean Android app with timeout protection to prevent hanging
# This script safely uninstalls the TimeSafari app from connected Android devices
# with a 30-second timeout to prevent indefinite hanging.

# Exit on any error
set -e

# Source common utilities
source "$(dirname "$0")/common.sh"

# Function to implement timeout for systems without timeout command
timeout_command() {
    local timeout_seconds="$1"
    shift
    
    # Check if timeout command exists
    if command -v timeout &> /dev/null; then
        timeout "$timeout_seconds" "$@"
    else
        # Fallback for systems without timeout (like macOS)
        # Use perl to implement timeout
        perl -e '
            eval {
                local $SIG{ALRM} = sub { die "timeout" };
                alarm shift;
                system @ARGV;
                alarm 0;
            };
            if ($@) { exit 1; }
        ' "$timeout_seconds" "$@"
    fi
}

log_info "Starting Android cleanup process..."

# Check if adb is available
if ! command -v adb &> /dev/null; then
    log_error "adb command not found. Please install Android SDK Platform Tools."
    exit 1
fi

# Check for connected devices
log_info "Checking for connected Android devices..."
if adb devices | grep -q 'device$'; then
    log_info "Android device(s) found. Attempting to uninstall app..."
    
    # Try to uninstall with timeout
    if timeout_command 30 adb uninstall app.timesafari.app; then
        log_success "Successfully uninstalled TimeSafari app"
    else
        log_warn "Uninstall failed or timed out after 30 seconds"
        log_info "This is normal if the app wasn't installed or device is unresponsive"
    fi
else
    log_info "No Android devices connected. Skipping uninstall."
fi

log_success "Android cleanup process completed"
