#!/bin/bash



########################################################################################
#                                 Pre-requisites                                       #
########################################################################################
# maso, 2025: check if the current directory is workspace root. The workspace
# root is the dirctory that contains the .venv/bin/bulk-pull.sh script (current script).
# If not, change the current directory to the workspace root.
# 
# The script may be a symbol link, we need to resolve the symbol link to get the actual 
# directory of the script.
# We must store current direcotry before changing it to the workspace root, because 
# we need to return to the original directory after pulling changes from the 
# repositories even there is error.
########################################################################################


function bulk_init_working_dir() {
    CURRENT_DIR="$(pwd)"
    SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
    SCRIPT_NAME="$(basename "$(readlink -f "$0")")"

    TEMP_DIR="$SCRIPT_DIR/../.."
    cd "$TEMP_DIR"
    WORKSPACE_ROOT="$(pwd)"

    # [] workspace root
    echo "Working director: $WORKSPACE_ROOT."
    echo "Current directory: $CURRENT_DIR."
    cd "$WORKSPACE_ROOT"
}


function bulk_init_temp_dir() {
    # Create a temporary directory to store the log file.
    WORKDIR="$(pwd)"
    TEMP_DIR="${WORKDIR}/.tmp"
    if [[ ! -d "$TEMP_DIR" ]]; then
        mkdir -p  "$TEMP_DIR"
    fi
    echo "Temporary directory: $TEMP_DIR."
}

function bulk_init_log_file() {
    WORKDIR="$(pwd)"
    PROCESS_DATE=$(date +%Y-%m-%d)
    LOG_FILE="${WORKDIR}/.tmp/${SCRIPT_NAME}-${PROCESS_DATE}.log"
    if [[ -f "$LOG_FILE" ]]; then
        rm -f "$LOG_FILE"
        touch "$LOG_FILE"
    fi
    echo "Log file: $LOG_FILE"
}

function bulk_init() {
    echo "#############################################################################"
    echo "Pre-requisites: Checking current directory and changing to workspace root if needed..."
    echo
    echo


    # Inintialize the working directory and log file.
    echo "Initializing working dircitories and log file..."
    echo
    bulk_init_working_dir
    bulk_init_temp_dir
    bulk_init_log_file

    echo
    echo
    echo "Pre-requisites check completed."
}

