#!/bin/bash

if [ $# -eq 0 ]; then
    echo "❌ No option provided."
    echo "👉 Please run the script with either:"
    echo "   ./check_oas_version.sh -version    # Show OAS version"
    echo "   ./check_oas_version.sh -patchinfo   # Show patch info"
    exit 1
fi

# OAS Version & Patch Check Script
# Usage:
#   ./oas_check.sh -version    → Get OAS version
#   ./oas_check.sh -patchinfo   → Get patch info
# Made by CVI

# --- Configuration ---
ORACLE_HOME="/u01/app/obiee"
PATCH_THRESHOLD_DAYS=90
VERSION_KEY=""
VERSION_FILE=""

# --- Functions ---

check_version() {
    if [ -z "$ORACLE_HOME" ] || [ ! -d "$ORACLE_HOME" ]; then
        echo "Error: ORACLE_HOME '$ORACLE_HOME' is not set or does not exist."
        exit 1
    fi

    if [ -f "$ORACLE_HOME/bi/modules/oracle.bi.versions/version.txt" ]; then
        VERSION_FILE="$ORACLE_HOME/bi/modules/oracle.bi.versions/version.txt"
        VERSION_KEY="oa_platform="
    elif [ -f "$ORACLE_HOME/bi/modules/oracle.bi.public/version.txt" ]; then
        VERSION_FILE="$ORACLE_HOME/bi/modules/oracle.bi.public/version.txt"
        VERSION_KEY="Release Version:"
    elif [ -f "$ORACLE_HOME/oracle_common/modules/oracle.fmwconfig/version.txt" ]; then
        VERSION_FILE="$ORACLE_HOME/oracle_common/modules/oracle.fmwconfig/version.txt"
        VERSION_KEY="Release Version:"
    elif [ -f "$ORACLE_HOME/version.txt" ]; then
        VERSION_FILE="$ORACLE_HOME/version.txt"
        VERSION_KEY="Release Version:"
    else
        echo "Error: No recognized version.txt found under ORACLE_HOME."
        exit 1
    fi

    version_line=$(grep "$VERSION_KEY" "$VERSION_FILE" | head -n 1)
    if [ -z "$version_line" ]; then
        echo "Error: '$VERSION_KEY' not found in $VERSION_FILE."
        echo "Contents of $VERSION_FILE:"
        cat "$VERSION_FILE"
        exit 1
    fi

    if [[ "$VERSION_KEY" == "oa_platform=" ]]; then
        version_number=$(echo "$version_line" | sed -n 's/^oa_platform=\([0-9.]*\)-.*$/\1/p')
    else
        version_number=$(echo "$version_line" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?')
    fi

    normalized_version=$(echo "$version_number" | awk -F. '{
        printf "%s", $1;
        for (i=2; i<=5; i++) {
            printf ".%s", ($i ? $i : "0");
        }
        printf "\n"
    }')

    case "$normalized_version" in
        12.2.1.4.0) oas_version="OAS 2023 (FMW Base)" ;;
        7.0.0.0.0)  oas_version="OAS 2023" ;;
        7.6.0.0.0)  oas_version="OAS 2024" ;;
        8.2.0.0.0)  oas_version="OAS 2025" ;;
        *)          oas_version="Unknown (Version: $normalized_version)" ;;
    esac

    echo "--- OAS Version Information ---"
    echo "Detected OAS version string: $version_number"
    echo "Normalized OAS version     : $normalized_version"
    echo "OAS Version interpreted    : $oas_version"
}

check_patch_info() {
    echo "--- Patch Information ---"

    PATH=$ORACLE_HOME/OPatch:$PATH; export PATH

    if [ ! -x "$ORACLE_HOME/OPatch/opatch" ]; then
        echo "Error: opatch not found or not executable at $ORACLE_HOME/OPatch/opatch."
        return
    fi

    today=$(date +%s)
    OPATCH_RESULT=$(timeout 120 "$ORACLE_HOME/OPatch/opatch" lsinventory 2>/dev/null | grep -i "applied on")
    OPATCH_STATUS=$?

    if [ $OPATCH_STATUS -eq 124 ]; then
        echo "Warning: opatch lsinventory timed out (120s)."
        return
    elif [ $OPATCH_STATUS -ne 0 ] && [ -z "$OPATCH_RESULT" ]; then
        echo "Error: opatch lsinventory failed (Exit Code: $OPATCH_STATUS)."
        return
    fi

    if [ -z "$OPATCH_RESULT" ]; then
        echo "No patches detected — OAS may never have been patched."
        return
    fi

    patch_dates=$(echo "$OPATCH_RESULT" | awk -F"applied on" '{print $2}' | xargs -I{} date -d "{}" +%s 2>/dev/null)
    if [ -z "$patch_dates" ]; then
        echo "No valid patch dates parsed — unexpected format in lsinventory output."
        return
    fi

    for patch_date in $patch_dates; do
        diff_days=$(( (today - patch_date) / 86400 ))
        if [ "$diff_days" -le "$PATCH_THRESHOLD_DAYS" ]; then
            echo "✅ Latest patch applied within the last $PATCH_THRESHOLD_DAYS days (≈$diff_days days ago)"
            return
        fi
    done

    echo "⚠️  No recent patch applied — all patches are older than $PATCH_THRESHOLD_DAYS days"
}

print_help() {
    echo "Usage: $0 [-version | -patchinfo]"
    echo "  -version    → Show OAS version"
    echo "  -patchinfo   → Show patch info (last patch date check)"
}

# --- Main ---
case "$1" in
    -version)   check_version ;;
    -patchinfo)  check_patch_info ;;
    *)          print_help ;;
esac
