#!/bin/bash

# Exit immediately if a command exits with a non-zero status.
set -e
# Treat unset variables as an error.
set -u
# The return value of a pipeline is the status of the last command to exit with a non-zero status, or zero if all commands exit successfully.
set -o pipefail

# --- CONFIGURATION ---
# IMPORTANT: Adjust this URL to match your website's domain!
BASE_URL="https://fid.intellihometech.com"
# ---------------------

# Define the output JSON file
JSON_FILE="workingOn.json"

# --- Script Options ---
VERBOSE_OUTPUT=false

# Function to display usage
usage() {
    echo "Usage: $0 <starting_directory> <directory_days_old> <files_days_old> [--verbose|-v]" >&2
    echo "" >&2
    echo "  <starting_directory>: The absolute or relative path to the directory to start scanning for projects." >&2
    echo "  <directory_days_old>: Integer. Only include directories modified less than this many days ago." >&2
    echo "  <files_days_old>: Integer. Only include projects that contain at least one file modified less than this many days ago." >&2
    echo "  --verbose, -v: Enable verbose output during script execution." >&2
    echo "" >&2
    echo "Example: $0 /home/intel145/websites/fid/ 7 8" >&2
    echo "  (Find directories newer than 7 days, containing files newer than 8 days, starting from /home/intel145/websites/fid/)" >&2
    exit 1
}

# Parse command-line arguments
START_DIR_INPUT="$1"
DIR_DAYS_OLD="$2"
FILE_DAYS_OLD="$3"

# Shift arguments to handle optional --verbose
shift 3 || usage # Shift positional arguments, exit if not enough
while (( "$#" )); do
    case "$1" in
        --verbose|-v)
            VERBOSE_OUTPUT=true
            echo "Verbose Output Mode: More details will be printed." >&2
            shift
            ;;
        *)
            echo "Error: Unknown option: $1" >&2
            usage
            ;;
    esac
done

# Validate required arguments
if [ -z "$START_DIR_INPUT" ] || [ -z "$DIR_DAYS_OLD" ] || [ -z "$FILE_DAYS_OLD" ]; then
    echo "Error: Missing required arguments." >&2
    usage
fi

# Validate numeric arguments
if ! [[ "$DIR_DAYS_OLD" =~ ^[0-9]+$ ]] || ! [[ "$FILE_DAYS_OLD" =~ ^[0-9]+$ ]]; then
    echo "Error: directory_days_old and files_days_old must be integers." >&2
    usage
fi

# Convert starting_directory to an absolute path for robust finding
WEB_ROOT=$(realpath "$START_DIR_INPUT" 2>/dev/null)
if [ $? -ne 0 ] || [ ! -d "$WEB_ROOT" ]; then
    echo "Error: Starting directory '$START_DIR_INPUT' does not exist or is not a valid directory." >&2
    exit 1
fi


# --- Main script execution ---
echo "Starting findNewProjects.sh script..."
echo "Scanning from: $WEB_ROOT"
echo "Directories modified less than: $DIR_DAYS_OLD days ago"
echo "Files modified less than: $FILE_DAYS_OLD days ago"
echo "Base URL for links: $BASE_URL"

# Initialize an empty array to store individual JSON object strings
APP_DATA_COLLECTED=()
# Initialize an array to store names of excluded directories
EXCLUDED_DIRS=()

# Collect all project directories into a temporary file first
TEMP_DIRS_FILE=$(mktemp)
if [ $? -ne 0 ]; then
    echo "Error: Failed to create temporary file for directory list." >&2
    exit 1
fi

if [ "$VERBOSE_OUTPUT" = true ]; then
    echo "Finding directories in '$WEB_ROOT' modified less than $DIR_DAYS_OLD days ago..." >&2
fi

# Find directories and write their null-terminated paths to the temporary file
find "$WEB_ROOT" -maxdepth 7 -type d -mtime -"$DIR_DAYS_OLD" -print0 > "$TEMP_DIRS_FILE" 2>/dev/null

# Read the null-separated paths from the temporary file into a bash array
mapfile -d $'\0' PROJECT_DIRS < "$TEMP_DIRS_FILE"

# Clean up the temporary file immediately
rm -f "$TEMP_DIRS_FILE"

# Loop through the array of discovered project directories
for project_dir in "${PROJECT_DIRS[@]}"; do
    # Debugging: Print the raw and quoted value of project_dir
    if [ "$VERBOSE_OUTPUT" = true ]; then
        echo "  DEBUG: Raw project_dir: [${project_dir}]" >&2
        printf "  DEBUG: Quoted project_dir: %q\n" "$project_dir" >&2
    fi

    # Skip empty strings that might result from `mapfile` processing
    if [ -z "$project_dir" ]; then
        continue
    fi

    # Skip WEB_ROOT itself if it's found (e.g., if WEB_ROOT is passed as a project)
    if [[ "$project_dir" == "$WEB_ROOT" ]]; then
        if [ "$VERBOSE_OUTPUT" = true ]; then
            echo "  Skipping base WEB_ROOT directory: $project_dir" >&2
        fi
        continue
    fi

    # --- Check for files modified less than FILE_DAYS_OLD within this project directory ---
    if [ "$VERBOSE_OUTPUT" = true ]; then
        echo "  Checking for files in '$project_dir' modified less than $FILE_DAYS_OLD days ago..." >&2
    fi
    # Use `find . -maxdepth 1 -type f -mtime -"$FILE_DAYS_OLD" -print -quit`
    # -print -quit: prints the first matching file and exits, making it efficient.
    # We redirect stderr to /dev/null to suppress "Permission denied" errors.
    if ! find "$project_dir" -maxdepth 1 -type f -mtime -"$FILE_DAYS_OLD" -print -quit 2>/dev/null | grep -q .; then
        if [ "$VERBOSE_OUTPUT" = true ]; then
            echo "    No recent files found in '$project_dir'. Skipping project." >&2
        fi
        EXCLUDED_DIRS+=("$(basename "$project_dir")") # Add to excluded list
        continue # Skip this project if no recent files
    fi

    # Extract app name from directory name
    app_name=$(basename "$project_dir")

    # Construct relative path from WEB_ROOT for URL generation
    # Ensure WEB_ROOT ends with a slash for consistent path trimming
    cleaned_web_root="${WEB_ROOT%/}/"
    relative_path="${project_dir#$cleaned_web_root}"

    # Determine startup link
    startup_link=""
    # 1. Check for index.php
    if [ -f "${project_dir}/index.php" ]; then
        startup_link="${BASE_URL}/${relative_path}/index.php"
    # 2. Check for index.html
    elif [ -f "${project_dir}/index.html" ]; then
        startup_link="${BASE_URL}/${relative_path}/index.html"
    else
        # 3. Look for the first PHP file in the directory
        # Using find with -maxdepth 1 and sorting to get a consistent "first" file
        first_php_file=$(find "${project_dir}" -maxdepth 1 -type f -name "*.php" | sort | head -n 1 2>/dev/null)
        if [ -n "$first_php_file" ]; then
            startup_link="${BASE_URL}/${relative_path}/$(basename "$first_php_file")"
        else
            # 4. Default to the directory URL if no suitable file is found
            startup_link="${BASE_URL}/${relative_path}/"
        fi
    fi

    # Secondary link and comment are harder to infer automatically,
    # so they will be empty or generic by default.
    secondary_link=""
    comment="Automatically discovered project."
    status="new" # Default status for newly discovered projects
    last_updated=$(date +"%Y-%m-%d") # The date the script is run

    if [ "$VERBOSE_OUTPUT" = true ]; then
        echo "  Processing App: '$app_name'" >&2
        echo "    Directory: $project_dir" >&2
        echo "    Startup Link: $startup_link" >&2
        echo "    Status: $status" >&2
    fi

    # Construct the JSON object string for the current project
    # Use printf for better control over newlines and quoting, and sed for escaping JSON values
    json_object=$(printf "{\n  \"appName\": \"%s\",\n  \"directory\": \"%s\",\n  \"startUp\": \"%s\",\n  \"secondaryLink\": \"%s\",\n  \"comment\": \"%s\",\n  \"status\": \"%s\",\n  \"lastUpdated\": \"%s\"\n}" \
        "$(echo "$app_name" | sed 's/"/\\"/g')" \
        "$(echo "$project_dir" | sed 's/"/\\"/g')" \
        "$(echo "$startup_link" | sed 's/"/\\"/g')" \
        "$(echo "$secondary_link" | sed 's/"/\\"/g')" \
        "$(echo "$comment" | sed 's/"/\\"/g')" \
        "$(echo "$status" | sed 's/"/\\"/g')" \
        "$(echo "$last_updated" | sed 's/"/\\"/g')" \
    )

    # Add the constructed JSON object string to the main array
    APP_DATA_COLLECTED+=("$json_object")

done

echo "Proceeding to update $JSON_FILE..."
# --- Backup existing JSON file ---
if [ -f "$JSON_FILE" ]; then
    TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
    BACKUP_FILE="${JSON_FILE}.bak.${TIMESTAMP}"
    cp "$JSON_FILE" "$BACKUP_FILE"
    if [ $? -eq 0 ]; then
        echo "Backed up $JSON_FILE to $BACKUP_FILE"
    else
        echo "Error: Failed to create backup of $JSON_FILE to $BACKUP_FILE." >&2
        exit 1 # Exit if backup fails
    fi
else
    echo "$JSON_FILE does not exist. Creating new file."
fi

# --- Write new JSON data to file ---
# Check if APP_DATA_COLLECTED is empty before writing to avoid creating "[]" if no projects found
if [ ${#APP_DATA_COLLECTED[@]} -eq 0 ]; then
    echo "No project data to write. Creating an empty JSON array in $JSON_FILE."
    echo "[]" > "$JSON_FILE"
else
    echo "[" > "$JSON_FILE"
    # Loop through the collected JSON object strings and write them
    for i in "${!APP_DATA_COLLECTED[@]}"; do
        echo "${APP_DATA_COLLECTED[$i]}" >> "$JSON_FILE"
        if [ "$i" -lt $(( ${#APP_DATA_COLLECTED[@]} - 1 )) ]; then
            echo "," >> "$JSON_FILE"
        fi
    done
    echo "]" >> "$JSON_FILE"
fi

if [ $? -eq 0 ]; then
    echo "Finished updating $JSON_FILE successfully."
else
    echo "Error: Failed to write to $JSON_FILE. Check permissions." >&2
    exit 1 # Exit if write fails
fi

echo "Script finished."

# --- Report Excluded Directories ---
if [ ${#EXCLUDED_DIRS[@]} -gt 0 ]; then
    echo ""
    echo "--- Directories Not Included Due to Age Filters ---"
    for excluded_dir in "${EXCLUDED_DIRS[@]}"; do
        echo "- $excluded_dir"
    done
    echo "---------------------------------------------------"
else
    echo ""
    echo "All eligible directories met the age criteria and were included."
fi

# Ask to view JSON file
read -p "Do you want to view the contents of $JSON_FILE? (y/N): " view_json
if [[ "$view_json" =~ ^[Yy]$ ]]; then
    echo "--- Contents of $JSON_FILE ---"
    cat "$JSON_FILE"
    echo "----------------------------"
fi

