#!/bin/bash

sourceCheckFiles() 
{
    local flag="$1"
    sourceInitilize $flag;

    # Checking for mising files
    local missing_files=()
    for file_to_source in "${files_to_source[@]}"; do
        if [ ! -f "${install_scripts_dir}${file_to_source}" ]; then
            missing_files+=("${install_scripts_dir}${file_to_source}")
            #echo "file_to_source ${install_scripts_dir}${file_to_source}"
        fi
    done

    # If there was no missing files
    if [ ${#missing_files[@]} -eq 0 ]; then
        # This is where the run command starts
        if [[ $flag == "run" ]]; then
            isSuccessful "All files found and loaded for startup."
            detectOS;
            # Fresh install (set by init.sh's completeInitMessage handoff): skip
            # the routine update check and go straight to startLoad. We just
            # installed the latest code — the update path's git-pull / release
            # re-fetch would fail on a tree without .git or a reachable manifest
            # and leave the WebUI / task-processor uninstalled. All of
            # checkUpdates' own success branches converge on startLoad anyway;
            # we just bypass the recovery gauntlet that doesn't apply here.
            if [[ "$LIBREPORTAL_INITIAL_INSTALL" == "1" ]]; then
                startLoad
            else
                checkUpdates
            fi
        # This is where the CLI command starts
        elif [[ $flag == "cli" ]]; then
            detectOS;
            cliInitialize;
        fi
    
    # Reinstall LibrePortal if there is missing files
    else
        isHeader "Missing LibrePortal Install Files"
        for missing_file in "${missing_files[@]}"; do
            echo "NOTICE : It seems that ${missing_file} is missing from your LibrePortal Installation."
        done
        echo ""
        echo "OPTION : 1. Reinstall LibrePortal"
        echo "OPTION : x. Exit"
        echo ""
        read -rp "Enter your choice (1 or 2) or 'x' to skip : " choice
        case "$choice" in
            1)
                runReinstall;
                exit 0  # Exit the entire script
            ;;
            [xX])
                # User chose to exit
                exit 1
            ;;
            *)
                isNotice "Invalid choice. Please enter 1, 2, or 'x'."
            ;;
        esac
    fi

}
