#!/bin/bash ################################################################################ # Script: preflight-check.sh # Description: Comprehensive pre-flight system validation for ROM Groomer. # Validates dependencies, system requirements, directory structure, # and configuration before running ROM operations. # # Usage: ./preflight-check.sh [--fix] [--verbose] # # Options: # --fix Attempt to automatically fix issues where possible # --verbose Show detailed information about checks # --help Show this help message # # Exit Codes: # 0 - All checks passed # 1 - Critical issues found # 2 - Warnings but system is usable # # Examples: # ./preflight-check.sh # Run basic checks # ./preflight-check.sh --fix # Run checks and auto-fix issues # ./preflight-check.sh --verbose --fix # Detailed output with auto-fix ################################################################################ # Script identification SCRIPT_NAME="preflight-check.sh" # Set umask to 000 to ensure files are created with 666 permissions umask 000 # Determine the directory of the current script SCRIPT_DIR="$(dirname "$(realpath "$0")")" # Determine the project root directory PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" # Load configuration and logger from the script's directory source "${PROJECT_ROOT}/core/config.sh" source "${PROJECT_ROOT}/core/logger.sh" source "${PROJECT_ROOT}/core/utils.sh" # Log the script name when it is called log "DEBUG" "Starting script: $(basename "$0")" # Global flags FIX_ISSUES=false VERBOSE=false CRITICAL_ISSUES=0 WARNINGS=0 TOTAL_CHECKS=0 # Colors for output RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' CYAN='\033[0;36m' BOLD='\033[1m' NC='\033[0m' # No Color # Function to display colored output print_color() { local color=$1 local message=$2 echo -e "${color}${message}${NC}" } # Function to increment check counters increment_check() { local result=$1 # "pass", "warn", or "fail" ((TOTAL_CHECKS++)) case $result in "fail") ((CRITICAL_ISSUES++)) ;; "warn") ((WARNINGS++)) ;; esac } # Function to check if a command exists check_command() { local cmd=$1 local required=$2 # "required" or "optional" local description=$3 if [[ "$VERBOSE" == "true" ]]; then print_color "$BLUE" "Checking: $description" fi if command -v "$cmd" >/dev/null 2>&1; then local version case $cmd in "bash") version=$(bash --version | head -n1 | cut -d' ' -f4) ;; "7z") version=$(7z | head -n2 | tail -n1 | grep -o '[0-9][0-9]*\.[0-9][0-9]*') ;; "rclone") version=$(rclone version 2>/dev/null | head -n1 | cut -d' ' -f2) ;; *) version="installed" ;; esac print_color "$GREEN" " ✓ $cmd ($version)" increment_check "pass" return 0 else if [[ "$required" == "required" ]]; then print_color "$RED" " ❌ $cmd (REQUIRED) - $description" increment_check "fail" if [[ "$FIX_ISSUES" == "true" ]]; then print_color "$YELLOW" " → Attempting to install $cmd..." case $cmd in "7z"|"p7zip") if command -v apt-get >/dev/null 2>&1; then sudo apt-get update && sudo apt-get install -y p7zip-full elif command -v yum >/dev/null 2>&1; then sudo yum install -y p7zip elif command -v pacman >/dev/null 2>&1; then sudo pacman -S p7zip fi ;; "rclone") curl https://rclone.org/install.sh | sudo bash ;; esac # Re-check after installation attempt if command -v "$cmd" >/dev/null 2>&1; then print_color "$GREEN" " ✓ Successfully installed $cmd" ((CRITICAL_ISSUES--)) else print_color "$RED" " ❌ Failed to install $cmd" fi fi return 1 else print_color "$YELLOW" " ⚠️ $cmd (optional) - $description" increment_check "warn" return 0 fi fi } # Function to check directory structure check_directory_structure() { print_color "$BOLD$BLUE" "=== Directory Structure Check ===" local base_dir="${EMUBASEDIR:-/data/emu}" local required_dirs=( "$base_dir/source" "$base_dir/filter" "$base_dir/org" "$base_dir/stage" "$base_dir/share" "$base_dir/lists" "$base_dir/temp" ) # Check base directory if [[ -d "$base_dir" ]]; then print_color "$GREEN" " ✓ Base directory exists: $base_dir" increment_check "pass" else print_color "$RED" " ❌ Base directory missing: $base_dir" increment_check "fail" if [[ "$FIX_ISSUES" == "true" ]]; then print_color "$YELLOW" " → Creating base directory..." if mkdir -p "$base_dir" 2>/dev/null; then print_color "$GREEN" " ✓ Created base directory" ((CRITICAL_ISSUES--)) else print_color "$RED" " ❌ Failed to create base directory" fi fi fi # Check required subdirectories for dir in "${required_dirs[@]}"; do if [[ -d "$dir" ]]; then if [[ -w "$dir" ]]; then print_color "$GREEN" " ✓ Directory accessible: $(basename "$dir")" increment_check "pass" else print_color "$YELLOW" " ⚠️ Directory not writable: $dir" increment_check "warn" if [[ "$FIX_ISSUES" == "true" ]]; then print_color "$YELLOW" " → Attempting to fix permissions..." if chmod 755 "$dir" 2>/dev/null; then print_color "$GREEN" " ✓ Fixed permissions" ((WARNINGS--)) else print_color "$RED" " ❌ Failed to fix permissions" fi fi fi else print_color "$YELLOW" " ⚠️ Directory missing: $(basename "$dir")" increment_check "warn" if [[ "$FIX_ISSUES" == "true" ]]; then print_color "$YELLOW" " → Creating directory..." if mkdir -p "$dir" 2>/dev/null; then print_color "$GREEN" " ✓ Created directory" ((WARNINGS--)) else print_color "$RED" " ❌ Failed to create directory" fi fi fi done } # Function to check system dependencies check_system_dependencies() { print_color "$BOLD$BLUE" "=== System Dependencies Check ===" # Check required tools print_color "$BOLD" "Required tools:" check_command "bash" "required" "Bash shell (version 4.0+)" check_command "find" "required" "File search utility" check_command "sort" "required" "Text sorting utility" check_command "uniq" "required" "Duplicate line removal" check_command "mkdir" "required" "Directory creation" check_command "cp" "required" "File copying" check_command "mv" "required" "File moving" check_command "rm" "required" "File removal" check_command "grep" "required" "Text pattern matching" check_command "awk" "required" "Text processing" check_command "sed" "required" "Stream editing" echo "" print_color "$BOLD" "Optional tools:" check_command "7z" "optional" "7-Zip archive handling" check_command "unzip" "optional" "ZIP archive extraction" check_command "rclone" "optional" "Remote file management" check_command "chdman" "optional" "CHD format conversion" check_command "curl" "optional" "HTTP transfers" check_command "wget" "optional" "Web file retrieval" check_command "rsync" "optional" "Efficient file copying" } # Function to check configuration files check_configuration() { print_color "$BOLD$BLUE" "=== Configuration Check ===" # Check config.sh if [[ -f "${SCRIPT_DIR}/config.sh" ]]; then if source "${PROJECT_ROOT}/core/config.sh" 2>/dev/null; then print_color "$GREEN" " ✓ config.sh loads successfully" increment_check "pass" else print_color "$RED" " ❌ config.sh has syntax errors" increment_check "fail" fi else print_color "$RED" " ❌ config.sh not found" increment_check "fail" fi # Check logger.sh if [[ -f "${SCRIPT_DIR}/logger.sh" ]]; then print_color "$GREEN" " ✓ logger.sh found" increment_check "pass" else print_color "$RED" " ❌ logger.sh not found" increment_check "fail" fi # Check utils.sh if [[ -f "${SCRIPT_DIR}/utils.sh" ]]; then print_color "$GREEN" " ✓ utils.sh found" increment_check "pass" else print_color "$RED" " ❌ utils.sh not found" increment_check "fail" fi # Check important environment variables if [[ -n "$EMUBASEDIR" ]]; then print_color "$GREEN" " ✓ EMUBASEDIR configured: $EMUBASEDIR" increment_check "pass" else print_color "$YELLOW" " ⚠️ EMUBASEDIR not set, using default" increment_check "warn" fi } # Function to check disk space check_disk_space() { print_color "$BOLD$BLUE" "=== Disk Space Check ===" local base_dir="${EMUBASEDIR:-/data/emu}" if [[ -d "$base_dir" ]]; then local available_space=$(df -h "$base_dir" | awk 'NR==2 {print $4}') local available_bytes=$(df "$base_dir" | awk 'NR==2 {print $4}') # Convert to GB for comparison (rough) local available_gb=$((available_bytes / 1024 / 1024)) if [[ $available_gb -gt 50 ]]; then print_color "$GREEN" " ✓ Sufficient disk space: $available_space available" increment_check "pass" elif [[ $available_gb -gt 10 ]]; then print_color "$YELLOW" " ⚠️ Limited disk space: $available_space available" increment_check "warn" else print_color "$RED" " ❌ Low disk space: $available_space available" increment_check "fail" fi else print_color "$YELLOW" " ⚠️ Cannot check disk space - base directory not found" increment_check "warn" fi } # Function to check permissions check_permissions() { print_color "$BOLD$BLUE" "=== Permissions Check ===" local base_dir="${EMUBASEDIR:-/data/emu}" # Test file creation local test_file="$base_dir/temp/preflight-test-$$" if mkdir -p "$base_dir/temp" 2>/dev/null && echo "test" > "$test_file" 2>/dev/null; then print_color "$GREEN" " ✓ File creation permissions working" rm -f "$test_file" 2>/dev/null increment_check "pass" else print_color "$RED" " ❌ Cannot create files in base directory" increment_check "fail" fi # Check script permissions if [[ -x "${SCRIPT_DIR}/sort2folders.sh" ]]; then print_color "$GREEN" " ✓ Scripts are executable" increment_check "pass" else print_color "$YELLOW" " ⚠️ Some scripts may not be executable" increment_check "warn" if [[ "$FIX_ISSUES" == "true" ]]; then print_color "$YELLOW" " → Making scripts executable..." if chmod +x "${SCRIPT_DIR}"/*.sh 2>/dev/null; then print_color "$GREEN" " ✓ Fixed script permissions" ((WARNINGS--)) else print_color "$RED" " ❌ Failed to fix script permissions" fi fi fi } # Function to run a quick functionality test check_functionality() { print_color "$BOLD$BLUE" "=== Functionality Test ===" # Test utils.sh functions if declare -f validate_directory >/dev/null 2>&1; then print_color "$GREEN" " ✓ Utility functions loaded" increment_check "pass" else print_color "$RED" " ❌ Utility functions not available" increment_check "fail" fi # Test logging system if log "DEBUG" "Test log message" >/dev/null 2>&1; then print_color "$GREEN" " ✓ Logging system working" increment_check "pass" else print_color "$YELLOW" " ⚠️ Logging system may have issues" increment_check "warn" fi } # Function to display final summary display_final_summary() { echo "" print_color "$CYAN" "════════════════════════════════════════════════════════════════════════════════" print_color "$BOLD$CYAN" " Pre-flight Check Summary" print_color "$CYAN" "════════════════════════════════════════════════════════════════════════════════" echo "" local passed_checks=$((TOTAL_CHECKS - CRITICAL_ISSUES - WARNINGS)) print_color "$GREEN" "✓ Passed checks: $passed_checks" if [[ $WARNINGS -gt 0 ]]; then print_color "$YELLOW" "⚠️ Warnings: $WARNINGS" fi if [[ $CRITICAL_ISSUES -gt 0 ]]; then print_color "$RED" "❌ Critical issues: $CRITICAL_ISSUES" fi echo "" print_color "$BOLD" "Total checks run: $TOTAL_CHECKS" echo "" # Determine exit status and recommendation if [[ $CRITICAL_ISSUES -gt 0 ]]; then print_color "$RED" "❌ RESULT: Critical issues found - ROM Groomer may not function properly" if [[ "$FIX_ISSUES" != "true" ]]; then print_color "$YELLOW" "💡 TIP: Run with --fix to automatically resolve some issues" fi echo "" print_color "$YELLOW" "Recommended actions:" print_color "$YELLOW" " 1. Fix critical issues shown above" print_color "$YELLOW" " 2. Run preflight check again" print_color "$YELLOW" " 3. Check the setup wizard: ./setup-wizard.sh" return 1 elif [[ $WARNINGS -gt 0 ]]; then print_color "$YELLOW" "⚠️ RESULT: Warnings found - ROM Groomer should work but may have limitations" echo "" print_color "$BLUE" "ROM Groomer is ready to use with minor limitations." return 2 else print_color "$GREEN" "✅ RESULT: All checks passed - ROM Groomer is ready to use!" echo "" print_color "$BLUE" "Next steps:" print_color "$BLUE" " • Run the setup wizard: ./setup-wizard.sh" print_color "$BLUE" " • Try organizing ROMs: ./sort2folders.sh " print_color "$BLUE" " • Build ROM collections: ./build-nes-usa-1g1r.sh" return 0 fi } # Function to display usage show_usage() { echo "Usage: $0 [--fix] [--verbose] [--help]" echo "" echo "ROM Groomer Pre-flight System Check" echo "" echo "Options:" echo " --fix Attempt to automatically fix issues where possible" echo " --verbose Show detailed information about each check" echo " --help Show this help message" echo "" echo "This script validates your system before running ROM operations." echo "It checks dependencies, directories, permissions, and configuration." } # Main function main() { # Parse command line arguments while [[ $# -gt 0 ]]; do case $1 in --fix) FIX_ISSUES=true shift ;; --verbose) VERBOSE=true shift ;; --help|-h) show_usage exit 0 ;; *) print_color "$RED" "Unknown option: $1" show_usage exit 1 ;; esac done # Display banner clear print_color "$CYAN" "════════════════════════════════════════════════════════════════════════════════" print_color "$BOLD$CYAN" " ROM Groomer Pre-flight Check" print_color "$CYAN" "════════════════════════════════════════════════════════════════════════════════" echo "" print_color "$BLUE" "Validating your system for ROM Groomer operations..." if [[ "$FIX_ISSUES" == "true" ]]; then print_color "$YELLOW" "Auto-fix mode enabled - will attempt to resolve issues" fi if [[ "$VERBOSE" == "true" ]]; then print_color "$BLUE" "Verbose mode enabled - showing detailed information" fi echo "" # Run all checks check_system_dependencies echo "" check_directory_structure echo "" check_configuration echo "" check_disk_space echo "" check_permissions echo "" check_functionality # Display final summary and exit local exit_code display_final_summary exit_code=$? exit $exit_code } # Show usage if called with --help even in non-interactive mode if [[ "$1" == "--help" || "$1" == "-h" ]]; then show_usage exit 0 fi # Run the main function with all arguments main "$@"