#!/bin/bash

get_centos_packages() {
    local MOUNT="$1"
    if [ -z "$MOUNT" ]; then
        echo "Usage: get_centos_packages <mount_point>"
        return 1
    fi

    # 检测 CentOS / RHEL 系列
    if [ ! -f "$MOUNT/etc/redhat-release" ]; then
        echo "[WARN] Non-CentOS/RHEL OS detected, exiting."
        return 1
    fi

    local LOG_DIR="$MOUNT/var/log"
    local PKG_LOGS=()

    # --------------------------
    # /var/log/yum.log 及历史日志
    # --------------------------
    for f in "$LOG_DIR"/yum.log*; do
        [ -f "$f" ] || continue
        echo "软件安装：文件路径 $f"
        while read -r line; do
            # 匹配安装包行，如：
            #  Oct 19 13:14:57 Installed: vim-enhanced-8.2.2637-18.el8.x86_64
            if [[ "$line" =~ Installed:\ ([^[:space:]]+) ]]; then
                PKG_LOGS+=("${BASH_REMATCH[1]}")
            fi
        done < "$f"
    done

    if [ "${#PKG_LOGS[@]}" -gt 0 ]; then
        printf '['
        for i in "${!PKG_LOGS[@]}"; do
            printf '"%s"' "${PKG_LOGS[$i]}"
            if [ "$i" -lt $((${#PKG_LOGS[@]}-1)) ]; then
                printf ', '
            fi
        done
        printf ']\n'
    else
        echo "未在 yum.log 文件中发现安装记录。"
    fi
}

list_dirs_and_files() {
    local MOUNT="$1"

    # 固定目录列表
    local DIR_LIST=(
        "/opt"
        "/"
        "/root"
        "/home"
        "/etc"
        "/var/lib"
        "/usr/local/share"
        "/usr/src"
        "/var/log"
    )

    echo "===== 目录和文件列表 ====="
    for d in "${DIR_LIST[@]}"; do
        local path="$MOUNT$d"
        echo "$d:"

        if [ ! -d "$path" ]; then
            echo "  (不存在)"
            echo
            continue
        fi

        local dirs=()
        local files=()
        for entry in "$path"/* "$path"/.*; do
            [ ! -e "$entry" ] && continue
            name="${entry##*/}"
            [ "$name" == "." ] || [ "$name" == ".." ] && continue
            if [ -d "$entry" ]; then
                dirs+=("$name")
            else
                files+=("$name")
            fi
        done

        # 输出目录列表
        echo "  目录: ${dirs[*]}"
        # 输出文件列表
        echo "  文件: ${files[*]}"
        echo
    done
}


show_bash_history() {
    local MOUNT="$1"
    local users=("root")

    for u in "${users[@]}"; do
        local hist_file="$MOUNT/home/$u/.bash_history"
        if [ "$u" == "root" ]; then
            hist_file="$MOUNT/root/.bash_history"
        fi

        echo "===== $u 的 Bash 历史记录 ====="
        if [ -f "$hist_file" ]; then
            cat "$hist_file"
        else
            echo "(未找到历史记录文件)"
        fi
        echo
    done
}


MOUNT_POINT="$1"
if [ -z "$MOUNT_POINT" ]; then
    echo "Usage: $0 <mount_point>"
    exit 1
fi

get_centos_packages $MOUNT_POINT
list_dirs_and_files $MOUNT_POINT
show_bash_history $MOUNT_POINT
