#!/usr/bin/env bash

# +-----------------------------------------------------------------------------
# | File:           oracle-dba-toolkit
# | Author:         Jeffrey M. Hunter
# | Description:    Oracle DBA Toolkit utility script.
# | Compatibility:  Bash version 4 or higher.
# | Coding style:   This script adheres to the Bash Script Style Guide
# |                 published by Google with several exceptions:
# |                 https://google.github.io/styleguide/shellguide.html
# | Requirements:   conf/toolkit-defaults.conf
# |                 functions/lib.sh
# |                 functions/json.sh
# | Documentation:  See: doc/README-oracle-dba-toolkit.txt
# | Call syntax:    Use "oracle-dba-toolkit --help" to see the help and options.
# | Repo:           https://gitlab.com/jeffreyhunter/oracle-dba-toolkit
# +---------------------------------------------------------------------------

# Script description
script_description="Oracle DBA Toolkit utility script."

# Set the ORACLE_DBA_TOOLKIT_HOME variable to the parent directory of the
# current script location
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ORACLE_DBA_TOOLKIT_HOME="$(dirname "$SCRIPT_DIR")"

# Import all common functions from the functions/ directory
pushd ${ORACLE_DBA_TOOLKIT_HOME} > /dev/null 2>&1
for file in functions/*.sh; do
    source "$file"
done
toolkit_version="$(get_toolkit_version ${toolkit_version_file})"
popd > /dev/null 2>&1
unset file

# ------------------------------------------------------------------------------
# Function definitions
# ------------------------------------------------------------------------------

#
# Function: usage
#
#   Print the usage information for the script to the console and exit.
#
# Usage:
#   usage
#
# Parameters:
#   None
#
# Return:
#   None
#
usage() {
    local script_name=${0##*/}

    echo -e "Usage: ${WHITE_BOLD}${script_name} [options ...]${RESET}"
    echo
    echo "${script_description}"
    echo
    echo -e "${YELLOW_BOLD}Toolkit Options:${RESET}"
    echo
    echo -e "  -V, --version                Print the toolkit version and exit"
    echo -e "  -c, --check-config           Perform all configuration checks"
    echo
    echo -e "${YELLOW_BOLD}Informative Options:${RESET}"
    echo
    echo -e "  -h, --help                   print usage and exit"
    echo
    echo -e "${WHITE_BOLD}For more information on usage:${RESET} ${GREEN}doc/README-oracle-dba-toolkit.txt${RESET}"
    echo
    exit 0
}

#
# Function: argument_parsing
#
#   Parse incoming arguments and set them to global variables for use in this
#   script.
#
# Usage:
#   argument_parsing "$@"
#
# Parameters:
#   $1 (string): Array of command-line arguments (can be accessed using the
#                special variable $@ that represents all the positional
#                parameters passed to this script).
#
# Return:
#   None
#
argument_parsing() {
    local script_name=${0##*/}

    show_copyright

    if [[ $# -eq 0 ]]; then
        echo
        echo "${script_description}"
        echo
        echo -e "${RED_BOLD}Missing options${RESET}"
        echo
        echo -e "Try '${GREEN}${script_name} --help${RESET}' for more information."
        echo
        exit 0
    fi

    while [[ $# -gt 0 ]]; do
        case "$1" in
            -h | --help)
                echo
                usage
            ;;
            -V | --version)
                echo
                print_version
                echo
                exit 0
            ;;
            -c | --check-config)
                check_config
            ;;
            *)
                echo
                echo_error "Unknown option '$1'"
                echo
                echo -e "Try '${GREEN}${script_name} --help${RESET}' to show usage."
                echo
                exit 1
            ;;
        esac
        shift
    done
}

# Function to print the version
print_version() {
    local toolkit_version
    toolkit_version="$(get_toolkit_version ${ORACLE_DBA_TOOLKIT_HOME}/${toolkit_version_file})"
    echo "Toolkit version: ${toolkit_version}"
}

# Function to display the currently logged-in user
print_logged_in_user() {
    local logged_in_user=$(whoami)
    echo "Currently logged-in user: $logged_in_user"
}

# Function to display the operating system
print_operating_system() {
    local os_info=$(uname -s)
    echo "Operating system: $os_info"
}

# Function to check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Function to perform all configuration checks
check_config() {
    local directory_to_check
    local commands
    local required_directories
    local required_files
    local errors_found
    local warnings_found

    echo
    echo "+-------------------------------------------------------------------+"
    echo "| Overview                                                          |"
    echo "+-------------------------------------------------------------------+"

    errors_found=0
    warnings_found=0

    echo
    print_version
    echo
    print_logged_in_user
    print_operating_system

    echo
    echo "+-------------------------------------------------------------------+"
    echo "| Starting Oracle DBA Toolkit checks...                             |"
    echo "+-------------------------------------------------------------------+"
    echo

    # Check if ORACLE_DBA_TOOLKIT_HOME is set
    if [ -z "$ORACLE_DBA_TOOLKIT_HOME" ]; then
        echo -e "Error: ORACLE_DBA_TOOLKIT_HOME environment variable is not set. ${RED}[Failed]${RESET}"
        errors_found=1
    else
        echo -e "ORACLE_DBA_TOOLKIT_HOME environment variable is set to $ORACLE_DBA_TOOLKIT_HOME. ${GREEN}[Passed]${RESET}"
    fi

    # Check if ORACLE_DBA_TOOLKIT_HOME directory exists
    if [ ! -d "$ORACLE_DBA_TOOLKIT_HOME" ]; then
        echo -e "Error: ORACLE_DBA_TOOLKIT_HOME directory $ORACLE_DBA_TOOLKIT_HOME does not exist. ${RED}[Failed]${RESET}"
        errors_found=1
    else
        echo -e "ORACLE_DBA_TOOLKIT_HOME directory $ORACLE_DBA_TOOLKIT_HOME exists. ${GREEN}[Passed]${RESET}"
    fi

    # Check if ORACLE_PATH is set
    if [ -z "$ORACLE_PATH" ]; then
        echo -e "Warning: ORACLE_PATH environment variable is not set. ${RED}[Failed]${RESET}"
        warnings_found=1
    else
        echo -e "ORACLE_PATH environment variable is set to [$ORACLE_PATH]. ${GREEN}[Passed]${RESET}"
    fi

    # Check if ORACLE_PATH is set correctly
    directory_to_check="${ORACLE_DBA_TOOLKIT_HOME}/sql"
    if [[ ":$ORACLE_PATH:" == *":$directory_to_check:"* ]]; then
        echo -e "Directory $directory_to_check exists in ORACLE_PATH. ${GREEN}[Passed]${RESET}"
    else
        echo -e "Warning: Directory $directory_to_check does not exist in ORACLE_PATH. ${RED}[Failed]${RESET}"
        warnings_found=1
    fi

    # Check if necessary commands are available
    commands=("sqlplus" "tnsping" "rman" "expdp")
    for cmd in "${commands[@]}"; do
        if command_exists "$cmd"; then
            echo -e "Command $cmd is available. ${GREEN}[Passed]${RESET}"
        else
            echo -e "Error: Command $cmd is not available. ${RED}[Failed]${RESET}"
            errors_found=1
        fi
    done

    # Check if optional commands are available
    commands=("/usr/lib/sendmail")
    for cmd in "${commands[@]}"; do
        if command_exists "$cmd"; then
            echo -e "Command $cmd is available. ${GREEN}[Passed]${RESET}"
        else
            echo -e "Warning: Command $cmd is not available. ${RED}[Failed]${RESET}"
            warnings_found=1
        fi
    done

    # Check for directories
    required_directories=("bin" "conf" "doc" "extproc" "functions" "lib" "log" "out" "plsql" "run" "sql" "temp")
    for directory in "${required_directories[@]}"; do
        if [ -d "$ORACLE_DBA_TOOLKIT_HOME/$directory" ]; then
            echo -e "Directory $directory is present. ${GREEN}[Passed]${RESET}"
        else
            echo -e "Error: Directory $directory is missing. ${RED}[Failed]${RESET}"
            errors_found=1
        fi
    done

    # Check for necessary files
    required_files=("bin/dpump-backup.sh" "bin/rman-backup.sh" "bin/crontab-example.txt" "conf/toolkit-defaults.conf" "functions/json.sh" "functions/lib.sh" "prepare-archive.sh" "VERSION" "README.md")
    for file in "${required_files[@]}"; do
        if [ -f "$ORACLE_DBA_TOOLKIT_HOME/$file" ]; then
            echo -e "File $file is present. ${GREEN}[Passed]${RESET}"
        else
            echo -e "Error: File $file is missing. ${RED}[Failed]${RESET}"
            errors_found=1
        fi
    done

    echo
    echo "+-------------------------------------------------------------------+"
    echo "| Status                                                            |"
    echo "+-------------------------------------------------------------------+"
    echo

    # Exit script
    if [ $errors_found == 1 ] && [ $warnings_found == 1 ]; then
        echo "Oracle DBA Toolkit configuration check completed with errors and warnings."
        echo
        exit 2
    elif [ $errors_found == 1 ]; then
        echo "Oracle DBA Toolkit configuration check completed with errors."
        echo
        exit 2
    elif [ $warnings_found == 1 ]; then
        echo "Oracle DBA Toolkit configuration check completed with warnings."
        echo
        exit 1
    else
        echo "Oracle DBA Toolkit configuration check completed successfully."
        echo
        exit 0
    fi
}

################################################################################
# main
################################################################################

set_script_variables_lib
argument_parsing "$@"
