#!/bin/bash

LOG="/var/log/cups/cups_monitor.log"
MODULE_DIR="/opt/print-control/modules/"
WATERMARK_MODULE_DIR="/opt/watermark-control/modules"
JOB_ID="$6"  # 假设第6个参数是打印任务的ID
CURRENT_TIME=$(date "+%Y-%m-%d %H:%M:%S")
REMOVE_JOB_LIST="/opt/print-control/pipes/remove_list"


# 设置全局变量
global_watermark_status=0
# 日志记录函数
log_message() {
    echo "--$(date) --: $1" >> "$LOG"
}

# 上报审计日志 参数: 1-6 $@ , 7 敏感信息数量, 8 结果
log_report() {
    file_path="$3"
    if [[ "$7" -ge "1" ]]; then
        message=$($MODULE_DIR/kydlp_t.sh "%s contains %d important items, printing %s." "$file_path" "$7" "$8")
    else
        message=$($MODULE_DIR/kydlp_t.sh "%s no sensitive information, printing %s." "$file_path" "$8")
    fi
    body="{\"created_time\":\"${CURRENT_TIME}\",\"time\":\"${CURRENT_TIME}\",\"name\":\"Print_Control\",\"user_name\":\"$2\",\"hostname\":\"$2\",\"lv\":\"debug\",\"message\":\"$message\"}"
    empty=$(gdbus call --system -o /org/log/sys_transmit -d org.log.sys_transmit -m org.log.transmit.log_transmit "${body}" & > /dev/null 2>&1)
}

# log_report() {
#     file_path="$3"
#     if [[ "$7" -ge "1" ]]; then
#         content="${file_path} 存在${7}个敏感信息，打印${8}。"
#     else
#         content="${file_path} 无敏感信息，打印${8}。"
#     fi
#     message="{\"content\":\"$content\",\"file_name\":\"文件名称\",\"file_path\":\"文件路径\",\"sensitive_word_search\":\"敏感字搜索\",\"print_result\":\"打印结果（成功，阻止，取消）\",\"detail\":[{\"sensitive_content\":\"\",\"num\":1212},{\"sensitive_content\":\"\",\"num\":1212}]}"
#     body='{"created_time":"'${CURRENT_TIME}'","time":"'${CURRENT_TIME}'","name":"Print_Control","user_name":"'$2'","hostname":"'$2'","lv":"debug","message": "{\\"content\\":\\"'${content}'\\",\\"detail\\":[{\\"sensitive_content\\":\\"保密\\",\\"num\\":1212},{\\"sensitive_content\\":\\"保密\\",\\"num\\":1212}]}"}'  
#     empty=$(gdbus call --system -o /org/log/sys_transmit -d org.log.sys_transmit -m org.log.transmit.log_transmit "${body}" & > /dev/null 2>&1)
# }

# 获取本地开关状态和策略规则
get_switch_and_rules() {
    global_switcher=$($MODULE_DIR/getswitch.sh)
    global_keywords=$($MODULE_DIR/getRules)
    log_message "打印管控开关状态- { $global_switcher }"
    log_message "打印规则名单- { $global_keywords }"
    printer_status=$(echo $global_switcher | cut -d ' ' -f 1)
    global_watermark_status=$(echo $global_switcher | cut -d ' ' -f 2)
    # echo "$printer_status"
    # echo "$watermark_status"
    log_message "打印管控开关状态- { $printer_status }"
    log_message "水印管控开关状态- { $global_watermark_status }"
}

# 获取文本内容和检查关键字
process_text_and_check_keywords() {
    keywords_text=$($MODULE_DIR/getpdftxt "$JOB_ID")
    python_output=$($MODULE_DIR/count_sensitive_words "$keywords_text" "$1")
    echo "$python_output"
}

# 发送通知
send_notification() {
    title="$1"
    content="$2"
    gdbus call --system -o /kydevmonit/Responser -d com.kylin.kydevmonit.hedronagent -m com.kylin.kydevmonit.hedronagent.show_system_notification "{\"title\": \"$title\", \"content\": \"$content\", \"urgency\": 1, \"timeout\": 9500}"
}

# 执行审计交互
wait_confirm(){
    # 审计 调用 小助手弹窗 传参: print_job_$id
    empty=$(gdbus call --system -o /kydevmonit/Responser -d com.kylin.kydevmonit.hedronagent -m com.kylin.kydevmonit.hedronagent.sensitive_printing_warning "$1")
    # 创建 socket文件， 等待监听，挂起打印任务 【用户在小助手操作】
    response=$(python3 /opt/print-control/modules/auditconfirm print_job_$1)
    echo "$response"
}

# 继续打印
# 继续打印
continue_print() {
    if [ -n "$6" ]; then
        log_message "---常规的打印---$1==$2==$3==$4==$5==$6"
        if [[ "$global_watermark_status" -ge 1 ]]; then
            log_message "开启打印管控水印模式"
            send_notification "$($MODULE_DIR/kydlp_t.sh "message notification")" "$($MODULE_DIR/kydlp_t.sh "You have turned on the watermark mode")"
            watermark_pdf "$@"    
        else 
            /usr/lib/cups/filter/pdftopdf "$1" "$2" "$3" "$4" "$5" "$6"
        fi
    else
        if [[ "$global_watermark_status" -ge 1 ]]; then
            log_message "开启打印管控水印模式"
            send_notification "$($MODULE_DIR/kydlp_t.sh "message notification")" "$($MODULE_DIR/kydlp_t.sh "You have turned on the watermark mode")"
            watermark_pdf "$@"    
        else 
            log_message "---打印测试页---$1==$2==$3==$4==$5==$6"
            /usr/lib/cups/filter/pdftopdf "$1" "$2" "$3" "$4" "$5"
        fi
    fi
}

# 取消打印
cancel_print() {
    empty=$(echo "$1"| socat - UNIX-CONNECT:$REMOVE_JOB_LIST & )
    sleep 1
    log_message "已取消打印 $1"
}
# 生成水印
watermark_pdf(){
    watermarkpdf_path=$($WATERMARK_MODULE_DIR/watermark "$6" "$2")
    log_message "打印水印-- watermark_pdf---- { $watermarkpdf_path }"
    /usr/lib/cups/filter/pdftopdf "$1" "$2" "$3" "$4" "$5" "$watermarkpdf_path"
}
# 主函数
# shellcheck disable=SC1073
main() {
    log_message "$1==$2==$3==$4==$5==$6"
    get_switch_and_rules
    switcher=$printer_status 
    # watermark_switcher=$watermark_status
    keywords=$global_keywords
    if [[ "$switcher" -ge 1 ]]; then
        keywords_matches=$(process_text_and_check_keywords "$keywords")
	      total=$(echo "$keywords_matches" | grep -oP '"total": \K\d+')
        if [[ "$total" -ge 1 ]]; then
            case "$switcher" in
                1)  # 阻断模式
                    send_notification "$($MODULE_DIR/kydlp_t.sh "message notification")" "$($MODULE_DIR/kydlp_t.sh "The file you printed has sensitive information and has been blocked from printing")"
                    log_message "监测到有{ $total }个关键字 阻止打印"
                    log_report "$@" $total "$($MODULE_DIR/kydlp_t.sh "prevent")"
                    cancel_print "$1"
                    return
                    ;;
                2)  # 审计模式
                    #send_notification "风险提示" "命中关键字总数：$total"
                    log_message "监测到有{ $total }个关键字 待确认"
                    response=$(wait_confirm "$1")
                    log_message "采用：{ $response}打印方式"
                    # 等待用户确认（这里假设使用某种方式等待用户响应）
                    if [[ "$response" == "yes"* ]]; then
                        continue_print "$@"
                        # shellcheck disable=SC2001
                        log_message "继续打印：$(echo "$3" | sed 's/ //g')"
                        log_report "$@" "$total" "$($MODULE_DIR/kydlp_t.sh "success")"
                        return
                    else
                        # shellcheck disable=SC2001
			            log_message "取消打印：$(echo "$3" | sed 's/ //g')"
			            log_report "$@" "$total" "$($MODULE_DIR/kydlp_t.sh "cancel")"
                        cancel_print "$1"
			            return
                    fi
                    ;;
                *)
                    log_message "开关错误."
                    return
                    ;;
            esac
        else
            continue_print "$@"
            log_message "无敏感信息，继续打印"
            log_report "$@" "0" "$($MODULE_DIR/kydlp_t.sh "success")"
            return
        fi
    else
        log_message "未开启打印管控"
        continue_print "$@"
    fi
}

# 调用主函数并传递参数
main "$@"