#!/bin/bash

SHADER_DIR="$HOME/.config/hypr/shaders"
SHADER_FILE="$SHADER_DIR/brightness.frag"

# Ensure shader directory exists
mkdir -p "$SHADER_DIR"

# Get screen brightness level
echo "Enter screen brightness level (0-10, where 10 = 100%):"
read -r LEVEL

# Validate input
if ! [[ "$LEVEL" =~ ^[0-9]+$ ]] || [ "$LEVEL" -lt 0 ] || [ "$LEVEL" -gt 10 ]; then
    echo "Invalid input. Please enter a number between 0 and 10."
    exit 1
fi

# Convert to decimal (0-10 -> 0.0-1.0)
BRIGHTNESS=$(echo "scale=2; $LEVEL / 10" | bc)

# Ask about keyboard backlight
echo "Adjust keyboard backlight? (y/n):"
read -r KBD_ADJUST

if [[ "$KBD_ADJUST" == "y" || "$KBD_ADJUST" == "Y" ]]; then
    echo "Enter keyboard backlight level (0-10, where 10 = 100%):"
    read -r KBD_LEVEL
    
    # Validate keyboard input
    if ! [[ "$KBD_LEVEL" =~ ^[0-9]+$ ]] || [ "$KBD_LEVEL" -lt 0 ] || [ "$KBD_LEVEL" -gt 10 ]; then
        echo "Invalid input. Please enter a number between 0 and 10."
        exit 1
    fi
    
    # Convert to percentage (0-10 -> 0-100)
    KBD_PERCENT=$((KBD_LEVEL * 10))
    
    # Set keyboard backlight
    kbdlight set $KBD_PERCENT
    echo "Keyboard backlight set to ${KBD_PERCENT}%"
fi

# Ask about blue light filter
echo "Apply blue light filter? (y/n):"
read -r BLUELIGHT

# Create shader based on choice
cat > "$SHADER_FILE" << EOF
#version 300 es

precision mediump float;

in vec2 v_texcoord;
out vec4 fragColor;
uniform sampler2D tex;

void main() {
    vec4 pixColor = texture(tex, v_texcoord);
    
EOF

if [[ "$BLUELIGHT" == "y" || "$BLUELIGHT" == "Y" ]]; then
    cat >> "$SHADER_FILE" << EOF
    // Reduce blue light
    pixColor.r *= 1.0;
    pixColor.g *= 0.85;
    pixColor.b *= 0.65;
    
EOF
fi

cat >> "$SHADER_FILE" << EOF
    // Adjust brightness
    pixColor.rgb *= $BRIGHTNESS;
    
    fragColor = pixColor;
}
EOF

# Apply shader
if [ -z "$HYPRLAND_INSTANCE_SIGNATURE" ]; then
    export HYPRLAND_INSTANCE_SIGNATURE=$(ls -t /tmp/hypr/ 2>/dev/null | head -n1)
fi
/usr/bin/hyprctl keyword decoration:screen_shader "$SHADER_FILE"

echo "Screen brightness set to ${LEVEL}0% $([ "$BLUELIGHT" == "y" ] || [ "$BLUELIGHT" == "Y" ] && echo "with blue light filter")"
