#!/usr/bin/env bash
set -euo pipefail

# 默认配置文件路径（RPM 安装后的路径）
DEFAULT_CONFIG="/etc/ks-prov-scanner/scan_config_init.json"
# 默认配置目录，可以在 /etc/ks-prov.conf 中覆盖
DEFAULT_DIR="/opt/ks-prov-dir"
DEFAULT_RESULT_DIR="${DEFAULT_DIR}/result"
CONFIG_FILE="/etc/ks-prov.conf"

if [[ -f "$CONFIG_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$CONFIG_FILE"
fi

mkdir -p "$DEFAULT_DIR" "$DEFAULT_RESULT_DIR"

# 注意: 进程互斥检查由Python代码通过文件锁实现，无需在Shell脚本中检查

# 检测语言环境（根据LANG环境变量）
detect_language() {
  local lang="${LANG:-}"
  if [[ "$lang" =~ ^zh ]]; then
    echo "zh_CN"
  else
    echo "en_US"
  fi
}

# 根据语言环境设置提示文本
LANG_CODE=$(detect_language)
if [[ "$LANG_CODE" == "zh_CN" ]]; then
  # 中文提示
  MSG_WIZARD="=== ks-prov-scanner 交互式向导 ==="
  MSG_TIP="提示: 输入 q 或 quit 可随时退出"
  MSG_EXIT="已退出"
  MSG_OUTPUT_PROMPT="1) 输出数据库文件路径"
  MSG_CONFIG_PROMPT="2) 扫描配置文件路径"
  MSG_MOUNT_PROMPT="3) 救援模式挂载点(留空表示不使用)"
  MSG_ERROR_CONFIG_NOT_FOUND="错误: 配置文件不存在"
  MSG_HINT_CONFIG="提示: 请确保配置文件存在，或使用 --config 参数指定正确的配置文件路径"
  MSG_EXECUTING=">> 即将执行:"
else
  # 英文提示
  MSG_WIZARD="=== ks-prov-scanner Interactive Wizard ==="
  MSG_TIP="Tip: Type 'q' or 'quit' to exit at any time"
  MSG_EXIT="Exited"
  MSG_OUTPUT_PROMPT="1) Output database file path"
  MSG_CONFIG_PROMPT="2) Scan configuration file path"
  MSG_MOUNT_PROMPT="3) Rescue mode mount point (leave empty to disable)"
  MSG_ERROR_CONFIG_NOT_FOUND="Error: Configuration file not found"
  MSG_HINT_CONFIG="Hint: Please ensure the configuration file exists, or use --config to specify the correct path"
  MSG_EXECUTING=">> About to execute:"
fi

print_help() {
  python3 -c "
import sys
sys.path.insert(0, '$(dirname "$(readlink -f "$0")")/../..')
from ks_prov_shared.i18n import t, set_language
set_language('$(detect_language)')
help_text = f'''{t('Configuration Scanner Tool ks-prov-scanner')}

{t('Description')}:
  {t('Collect system configuration information and store it in SQLite database, including')}:
  - {t('File contents and attributes')}
  - {t('System command execution results')}
  - {t('Service status and configuration')}
  - {t('Software package information')}

{t('Usage')}:
  ks-prov-scanner                    # {t('Enter interactive wizard mode')}
  ks-prov-scanner -h|--help          # {t('Show this help message')}

{t('Interactive Parameters')}:
  1) {t('Output database file path')}
     {t('Specify the SQLite database file path to generate')}
     {t('Default')}: current.db
     {t('Tips')}:
       - {t('If you input a directory path, current.db will be automatically appended')}
       - {t('To generate baseline.db, explicitly input the full path (e.g. /opt/baseline.db)')}

  2) {t('Scan configuration file path')}
     {t('Specify the scan configuration file (JSON format)')}
     {t('Default')}: /etc/ks-prov-scanner/scan_config_init.json
     {t('Tip')}: {t('The configuration file defines files, commands, services to scan, etc.')}

  3) {t('Rescue mode mount point')}
     {t('Specify the system root mount point in rescue mode')}
     {t('Default')}: {t('Empty (not using rescue mode)')}
     {t('Tip')}: e.g. /mnt/sysroot

{t('Command Line Mode (Advanced Usage)')}:
  python -m ks_prov_scanner.scanner_cli scan \\
    --output <database_path> \\
    --config <config_file_path> \\
    [--mount-point <mount_point>]

{t('Parameters')}:
  --output OUTPUT       {t('Output SQLite database path (required)')}
  --config CONFIG       {t('Scan configuration file path (JSON format, optional)')}
  --mount-point MOUNT_POINT
                        {t('Root mount path in rescue mode (optional)')}

{t('Examples')}:
  # {t('Scan current system with default configuration')}
  ks-prov-scanner
  # {t('Interactive input')}:
  # 1) /opt/baseline.db
  # 2) [{t('Press Enter to use default config')}]
  # 3) [{t('Press Enter to not use rescue mode')}]

{t('Output Description')}:
  {t('The generated database file can be used for subsequent configuration comparison analysis')}

{t('More Information')}:
  {t('Default configuration file')}: /etc/ks-prov-scanner/scan_config_init.json
'''
print(help_text)
" 2>/dev/null || cat <<'EOF'
ks-prov-scanner - Configuration Scanner Tool

Description:
  Collect system configuration information and store it in SQLite database, including:
  - File contents and attributes
  - System command execution results
  - Service status and configuration
  - Software package information

Usage:
  ks-prov-scanner                    # Enter interactive wizard mode
  ks-prov-scanner -h|--help          # Show this help message

Interactive Parameters:
  1) Output database file path
     Specify the SQLite database file path to generate
     Default: current.db
     Tips:
       - If you input a directory path, current.db will be automatically appended
       - To generate baseline.db, explicitly input the full path (e.g. /opt/baseline.db)

  2) Scan configuration file path
     Specify the scan configuration file (JSON format)
     Default: /etc/ks-prov-scanner/scan_config_init.json
     Tip: The configuration file defines files, commands, services to scan, etc.

  3) Rescue mode mount point
     Specify the system root mount point in rescue mode
     Default: Empty (not using rescue mode)
     Tip: e.g. /mnt/sysroot

Command Line Mode (Advanced Usage):
  python -m ks_prov_scanner.scanner_cli scan \
    --output <database_path> \
    --config <config_file_path> \
    [--mount-point <mount_point>]

Parameters:
  --output OUTPUT       Output SQLite database path (required)
  --config CONFIG       Scan configuration file path (JSON format, optional)
  --mount-point MOUNT_POINT
                        Root mount path in rescue mode (optional)

Examples:
  # Scan current system with default configuration
  ks-prov-scanner
  # Interactive input:
  # 1) /opt/baseline.db
  # 2) [Press Enter to use default config]
  # 3) [Press Enter to not use rescue mode]

Output Description:
  The generated database file can be used for subsequent configuration comparison analysis

More Information:
  Default configuration file: /etc/ks-prov-scanner/scan_config_init.json
EOF
}

if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then
  print_help
  exit 0
fi

echo "$MSG_WIZARD"
echo "$MSG_TIP"
echo ""

# 检查退出命令的辅助函数
check_exit() {
  local input="$1"
  # 只有在输入不为空时才检查退出命令
  if [[ -n "$input" ]] && [[ "${input,,}" == "q" || "${input,,}" == "quit" ]]; then
    echo "$MSG_EXIT"
    exit 0
  fi
}

# 清理输入：去除前后空格和控制字符（包括Tab）
clean_input() {
  local input="$1"
  # 去除前后空格
  input=$(echo "$input" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
  # 去除控制字符（包括Tab、回车等）
  input=$(echo "$input" | tr -d '\000-\037')
  echo "$input"
}

# 输出和结果默认路径
DEFAULT_DB_FILE="${DEFAULT_DIR}/current.db"

read -erp "$MSG_OUTPUT_PROMPT [${DEFAULT_DB_FILE}]: " OUTPUT_PATH
OUTPUT_PATH=$(clean_input "$OUTPUT_PATH")
check_exit "$OUTPUT_PATH"
OUTPUT_PATH=${OUTPUT_PATH:-$DEFAULT_DB_FILE}
# 如果输入的是目录或以 / 结尾，自动添加默认文件名
if [[ -d "$OUTPUT_PATH" ]] 2>/dev/null || [[ "$OUTPUT_PATH" == */ ]]; then
  OUTPUT_PATH="${OUTPUT_PATH%/}/current.db"
fi

read -erp "$MSG_CONFIG_PROMPT [${DEFAULT_CONFIG}]: " CONFIG_PATH
CONFIG_PATH=$(clean_input "$CONFIG_PATH")
check_exit "$CONFIG_PATH"
CONFIG_PATH=${CONFIG_PATH:-$DEFAULT_CONFIG}
# 检查配置文件是否存在
if [[ ! -f "$CONFIG_PATH" ]]; then
  echo "$MSG_ERROR_CONFIG_NOT_FOUND: $CONFIG_PATH" >&2
  echo "$MSG_HINT_CONFIG" >&2
  exit 1
fi

read -erp "$MSG_MOUNT_PROMPT []: " MOUNT_POINT
MOUNT_POINT=$(clean_input "$MOUNT_POINT")
check_exit "$MOUNT_POINT"

CMD=(python -m ks_prov_scanner.scanner_cli scan --output "$OUTPUT_PATH" --config "$CONFIG_PATH")
if [[ -n "${MOUNT_POINT}" ]]; then
  CMD+=(--mount-point "$MOUNT_POINT")
fi

echo "$MSG_EXECUTING ${CMD[*]}"
"${CMD[@]}"

