#!/bin/bash

# ============================================================
# 用法: ./script.sh [zh-CN|zh-HK|en-US]
# 默认语言: zh-CN
# ============================================================

LANG_CODE="${1:-zh-CN}"

# 校验语言参数
case "$LANG_CODE" in
    zh-CN|zh-HK|en-US) ;;
    *)
        echo "{\"timestamp\":\"$(date '+%Y-%m-%d %H:%M:%S')\",\"service\":\"none\",\"action\":\"restart\",\"status\":\"failed\",\"message\":\"Unsupported language: ${LANG_CODE}. Use zh-CN, zh-HK or en-US\"}"
        exit 1
        ;;
esac

# 国际化消息定义
get_message() {
    local key="$1"
    case "$LANG_CODE" in
        zh-CN)
            case "$key" in
                restart_success)    echo "重启成功" ;;
                restart_failed)     echo "重启异常，请检查服务状态或sudo免密权限" ;;
                service_not_found)  echo "采集服务不存在" ;;
            esac
            ;;
        zh-HK)
            case "$key" in
                restart_success)    echo "重啟成功" ;;
                restart_failed)     echo "重啟異常，請檢查服務狀態或sudo免密權限" ;;
                service_not_found)  echo "採集服務不存在" ;;
            esac
            ;;
        en-US)
            case "$key" in
                restart_success)    echo "Restart successful" ;;
                restart_failed)     echo "Restart failed, please check service status or sudo nopasswd permission" ;;
                service_not_found)  echo "Collection service not found" ;;
            esac
            ;;
    esac
}

# 输出 JSON
output_json() {
    local service="$1"
    local status="$2"
    local msg_key="$3"
    local message
    message=$(get_message "$msg_key")
    local timestamp
    timestamp=$(date '+%Y-%m-%d %H:%M:%S')

    echo "{\"timestamp\":\"${timestamp}\",\"lang\":\"${LANG_CODE}\",\"service\":\"${service}\",\"action\":\"restart\",\"status\":\"${status}\",\"message\":\"${message}\"}"
}

# ============================================================
# 主逻辑
# ============================================================

# 检测可用的采集服务（优先 perseusZ_server，回退 zabbix_server）
if systemctl cat perseusZ_server >/dev/null 2>&1; then
    svr_name="perseusZ_server"
elif systemctl cat zabbix_server >/dev/null 2>&1; then
    svr_name="zabbix_server"
else
    output_json "none" "failed" "service_not_found"
    exit 1
fi

# 根据当前用户选择重启方式（root 直接执行，否则使用 sudo 免密）
cur_user=$(whoami)
if [[ "${cur_user}" == "root" ]]; then
    systemctl restart "${svr_name}"
else
    sudo -n systemctl restart "${svr_name}"
fi

if [ $? -eq 0 ]; then
    output_json "${svr_name}" "success" "restart_success"
else
    output_json "${svr_name}" "failed" "restart_failed"
    exit 1
fi
