source "$(dirname "${BASH_SOURCE[0]}")/env-init.sh"
#!/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

# --- ANSI Color Codes ---
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# ------------------------

# --- 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
START_DIR_INPUT=""
DIR_DAYS_OLD=""
FILE_DAYS_OLD=""
MAX_DEPTH_ARG=3 # Default maxdepth to 3

# Function to display usage
usage() {
    echo -e "${BLUE}--- Script Usage ---${NC}" >&2
    echo "Usage: ${0##*/} <starting_directory> <directory_days_old> <files_days_old> [--max-depth <depth>] [--verbose|-v]" >&2
    echo "" >&2
    echo "  ${YELLOW}<starting_directory>${NC}: The absolute or relative path to the directory to start scanning for projects." >&2
    echo "  ${YELLOW}<directory_days_old>${NC}: Integer. Only include directories modified less than this many days ago." >&2
    echo "  ${YELLOW}<files_days_old>${NC}: Integer. Only include projects that contain at least one file modified less than this many days ago." >&2
    echo "  ${BLUE}--max-depth, -d <depth>${NC}: Integer. Maximum depth for directory scanning (default: ${MAX_DEPTH_ARG})." >&2
    echo "  ${BLUE}--verbose, -v${NC}: Enable verbose output during script execution." >&2
    echo "" >&2
    echo "Example: ${0##*/} /home/intel145/websites/fid/ 7 8 --max-depth 2" >&2
    echo "         ${0##*/} ../.. 7 7 -d 2" >&2
    echo "  (The first example finds directories newer than 7 days, containing files newer than 8 days," >&2
    echo "   starting from /home/intel145/websites/fid/, searching up to 2 levels deep.)" >&2
    echo -e "${BLUE}--------------------${NC}" >&2
    exit 1
}

# Parse command-line arguments
# First, parse the mandatory positional arguments
if [ "$#" -lt 3 ]; then
    echo -e "${RED}Error: Missing required positional arguments.${NC}" >&2
    usage
fi

START_DIR_INPUT="$1"
DIR_DAYS_OLD="$2"
FILE_DAYS_OLD="$3"
shift 3 # Shift off the positional arguments

# Now parse optional named arguments
while (( "$#" )); do
    case "$1" in
        --max-depth|-d)
            if [ -n "$2" ] && [[ "$2" =~ ^[0-9]+$ ]]; then
                MAX_DEPTH_ARG="$2"
                shift 2
            else
                echo -e "${RED}Error: Argument for $1 is missing or invalid. Must be an integer.${NC}" >&2
                usage
            fi
            ;;
        --verbose|-v)
            VERBOSE_OUTPUT=true
            echo -e "${YELLOW}Verbose Output Mode: More details will be printed.${NC}" >&2
            shift
            ;;
        --) # End of arguments
            shift
            break
            ;;
        -*) # Unknown option
            echo -e "${RED}Error: Unknown option: $1${NC}" >&2
            usage
            ;;
        *) # Positional arguments (should not happen with required named args)
            echo -e "${RED}Error: Unexpected argument: $1${NC}" >&2
            usage
            ;;
    esac
done

# Validate numeric arguments
if ! [[ "$DIR_DAYS_OLD" =~ ^[0-9]+$ ]] || ! [[ "$FILE_DAYS_OLD" =~ ^[0-9]+$ ]]; then
    echo -e "${RED}Error: directory_days_old and files_days_old must be integers.${NC}" >&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 -e "${RED}Error: Starting directory '$START_DIR_INPUT' does not exist or is not a valid directory.${NC}" >&2
    exit 1
fi


# --- Main script execution ---
echo -e "${BLUE}--- Starting findNewProjects.sh ---${NC}"
echo -e "${BLUE}Scanning from:${NC} $WEB_ROOT (Max Depth: ${YELLOW}$MAX_DEPTH_ARG${NC})"
echo -e "${BLUE}Directories modified less than:${NC} ${YELLOW}$DIR_DAYS_OLD days ago${NC}"
echo -e "${BLUE}Files modified less than:${NC} ${YELLOW}$FILE_DAYS_OLD days ago${NC}"
echo -e "${BLUE}Base URL for links:${NC} $BASE_URL"
echo -e "${BLUE}-----------------------------------${NC}"

# 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 -e "${RED}Error: Failed to create temporary file for directory list.${NC}" >&2
    exit 1
fi

if [ "$VERBOSE_OUTPUT" = true ]; then
    echo -e "${YELLOW}Finding directories in '$WEB_ROOT' (maxdepth $MAX_DEPTH_ARG) modified less than $DIR_DAYS_OLD days ago...${NC}" >&2
fi

# Find directories and write their null-terminated paths to the temporary file
find "$WEB_ROOT" -maxdepth "$MAX_DEPTH_ARG" -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
    # 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 -e "  ${YELLOW}Skipping base WEB_ROOT directory:${NC} $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 -e "  ${BLUE}Checking for files in '${project_dir}' modified less than ${FILE_DAYS_OLD} days ago...${NC}" >&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 -e "    ${YELLOW}No recent files found in '${project_dir}'. Skipping project.${NC}" >&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 and its modification date
    startup_file_path=""
    startup_link=""
    startup_file_modified=""

    # 1. Check for index.php
    if [ -f "${project_dir}/index.php" ]; then
        startup_file_path="${project_dir}/index.php"
        startup_link="${BASE_URL}/${relative_path}/index.php"
    # 2. Check for index.html
    elif [ -f "${project_dir}/index.html" ]; then
        startup_file_path="${project_dir}/index.html"
        startup_link="${BASE_URL}/${relative_path}/index.html"
    else
        # 3. Look for the newest PHP file in the directory
        # Using find with -maxdepth 1, -printf '%T@ %p\n' to get timestamp and path, then sort numerically
        newest_php_file_info=$(find "${project_dir}" -maxdepth 1 -type f -name "*.php" -printf '%T@ %p\n' 2>/dev/null | sort -nr | head -n 1)
        if [ -n "$newest_php_file_info" ]; then
            # Extract path from "timestamp /path/to/file.php"
            newest_php_file_path=$(echo "$newest_php_file_info" | cut -d' ' -f2-)
            startup_file_path="$newest_php_file_path"
            startup_link="${BASE_URL}/${relative_path}/$(basename "$newest_php_file_path")"
        else
            # 4. Default to the directory URL if no suitable file is found
            startup_link="${BASE_URL}/${relative_path}/"
        fi
    fi

    # Get startup file modification date/time if a file path was identified
    if [ -n "$startup_file_path" ] && [ -f "$startup_file_path" ]; then
        startup_file_modified=$(stat -c %y "$startup_file_path" | cut -d'.' -f1) # Get full date and time
    else
        startup_file_modified="N/A"
    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 -e "  ${GREEN}Processing App: '${app_name}'${NC}" >&2
        echo "    Directory: $project_dir" >&2
        echo "    Startup Link: $startup_link" >&2
        echo "    Startup File Modified: $startup_file_modified" >&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  \"startUpFileModified\": \"%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')" \
        "$(echo "$startup_file_modified" | sed 's/"/\\"/g')" \
    )

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

done

echo -e "${BLUE}--- Updating ${JSON_FILE} ---${NC}"
# --- 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 -e "${GREEN}Backed up ${JSON_FILE} to ${BACKUP_FILE}${NC}"
    else
        echo -e "${RED}Error: Failed to create backup of ${JSON_FILE} to ${BACKUP_FILE}.${NC}" >&2
        exit 1 # Exit if backup fails
    fi
else
    echo -e "${YELLOW}${JSON_FILE} does not exist. Creating new file.${NC}"
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 -e "${YELLOW}No project data to write. Creating an empty JSON array in ${JSON_FILE}.${NC}"
    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 -e "${GREEN}Finished updating ${JSON_FILE} successfully.${NC}"
else
    echo -e "${RED}Error: Failed to write to ${JSON_FILE}. Check permissions.${NC}" >&2
    exit 1 # Exit if write fails
fi

echo -e "${BLUE}--- Script Finished ---${NC}"

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

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

