#!/bin/bash

# 系统亮度调节脚本
# 使用 gsettings 命令设置银河麒麟系统的屏幕亮度

# 设置环境变量
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$(id -u)/bus"
export DISPLAY=:0

SCHEMA="org.ukui.power-manager"
KEY="brightness-ac"

# 显示使用帮助
show_help() {
    echo "使用方法: $0 <命令> [参数]"
    echo ""
    echo "命令:"
    echo "  get          获取当前亮度值"
    echo "  set          设置亮度值"
    echo "  -h, --help   显示帮助信息"
    echo ""
    echo "set 参数:"
    echo "  <value>      亮度值 (0.0-100.0)"
    echo ""
    echo "示例:"
    echo "  $0 get                    # 获取当前亮度"
    echo "  $0 set 76.1              # 设置亮度为 76.1"
    echo "  $0 set 50                # 设置亮度为 50"
}

# 验证参数
validate_args() {
    if [ -z "$1" ]; then
        echo "错误: 缺少命令"
        show_help
        exit 1
    fi
    
    case "$1" in
        set)
            if [ $# -ne 2 ]; then
                echo "错误: set 需要 1 个参数"
                show_help
                exit 1
            fi
            if ! [[ "$2" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
                echo "错误: 亮度值必须是数字"
                show_help
                exit 1
            fi
            local value=$(echo "$2" | bc -l 2>/dev/null || echo "$2")
            if (( $(echo "$value < 0" | bc -l) )) || (( $(echo "$value > 100" | bc -l) )); then
                echo "错误: 亮度值必须在 0.0 到 100.0 之间"
                show_help
                exit 1
            fi
            ;;
        get)
            if [ $# -ne 1 ]; then
                echo "错误: get 不需要参数"
                show_help
                exit 1
            fi
            ;;
        *)
            echo "错误: 未知命令 '$1'"
            show_help
            exit 1
            ;;
    esac
}

# 获取当前亮度
get_brightness() {
    local brightness=$(gsettings get $SCHEMA $KEY 2>/dev/null)
    
    if [ $? -eq 0 ]; then
        echo "当前亮度: $brightness"
        return 0
    else
        echo "获取亮度失败"
        exit 1
    fi
}

# 设置亮度
set_brightness() {
    local value="$1"
    
    echo "设置亮度: $value"
    
    gsettings set $SCHEMA $KEY "$value"
    
    if [ $? -eq 0 ]; then
        echo "亮度设置成功"
    else
        echo "亮度设置失败"
        exit 1
    fi
}

# 主函数
main() {
    # 检查是否请求帮助
    if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
        show_help
        exit 0
    fi
    
    # 验证参数
    validate_args "$@"
    
    # 执行命令
    case "$1" in
        get)
            get_brightness
            ;;
        set)
            set_brightness "$2"
            ;;
    esac
}

# 执行主函数
if [ "$0" = "$BASH_SOURCE" ]; then
    main "$@"
fi
