#!/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/../.."
    # resolve absolute path of TEMP_DIR without changing the current directory
    ABS_TEMP_DIR="$(readlink -f "$TEMP_DIR" 2>/dev/null || realpath "$TEMP_DIR" 2>/dev/null || (cd "$TEMP_DIR" 2>/dev/null && pwd -P))"
    if [[ -z "$ABS_TEMP_DIR" ]]; then
        echo "Error: cannot resolve absolute path of $TEMP_DIR" >&2
        exit 1
    fi

    # ensure subsequent $(pwd) yields the full TEMP_DIR path while keeping the shell's cwd unchanged
    export WORKSPACE_ROOT="$ABS_TEMP_DIR"

    cd "$CURRENT_DIR" || { echo "Warning: failed to return to $CURRENT_DIR" >&2; }

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


function bulk_init_temp_dir() {
    # Create a temporary directory to store the log file.
    WORKDIR="$WORKSPACE_ROOT"
    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="$WORKSPACE_ROOT"
    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_users() {
    # Intilize the worker user name. If the worker user is set in the .env file, use it.
    # Otherwise, use the current user name.
    CURRENT_USER="$(whoami)"
    WORKER_USER="${WORKER_USER:-$CURRENT_USER}"
}

function bulk_load_env_file() {
    # Load the environment variables from the .env file if it exists.
    ENV_FILE="$WORKSPACE_ROOT/.env"
    if [[ -f "$ENV_FILE" ]]; then
        # shellcheck source=/dev/null
        source "$ENV_FILE"
        echo "Environment variables loaded from $ENV_FILE."
    else
        echo "No .env file found at $ENV_FILE, skipping loading environment variables."
    fi
}


function bulk_init() {
    echo "Initializing working dircitories and log file..."
    echo
    bulk_init_working_dir
    bulk_init_temp_dir
    bulk_init_log_file
    bulk_load_env_file
    bulk_init_users
    echo
    echo "Pre-requisites check completed."
}


function bulk_switch_to_worker(){
    if [[ "$WORKER_USER" != "$(whoami)" ]]; then
        # run as worker (reload)
        if command -v sudo >/dev/null 2>&1; then
            exec sudo -u "$WORKER_USER" -H bash "$0" "$@"
        else
            echo "Error: sudo is required to run as user '$WORKER_USER'." >&2
            exit 1
        fi
    fi
}

function run_otoolbox_as_worker() {
    if [[ "$WORKER_USER" == "$(whoami)" ]]; then
        otoolbox "$@"
        return
    fi

    local worker_home
    worker_home="$(getent passwd "$WORKER_USER" | cut -d: -f6)"

    if [[ -z "$worker_home" ]]; then
        echo "Error: unable to resolve home directory for user '$WORKER_USER'." >&2
        return 1
    fi

    local worker_path
    worker_path="$worker_home/.local/bin:/usr/local/bin:/usr/bin:/bin"

    sudo -u "$WORKER_USER" -H env PATH="$worker_path" otoolbox "$@"
}

function run_git_as_worker() {
    if [[ "$WORKER_USER" == "$(whoami)" ]]; then
        git "$@"
        return
    fi

    local worker_home
    worker_home="$(getent passwd "$WORKER_USER" | cut -d: -f6)"

    if [[ -z "$worker_home" ]]; then
        echo "Error: unable to resolve home directory for user '$WORKER_USER'." >&2
        return 1
    fi

    local worker_path
    worker_path="$worker_home/.local/bin:/usr/local/bin:/usr/bin:/bin"

    sudo -u "$WORKER_USER" -H env PATH="$worker_path" git "$@"
}

# Init the working directory, log file and users.
bulk_init "$@"
