#!/bin/bash

# Path to the brightness shader file
SHADER_DIR="$HOME/.config/hypr/shaders"
SHADER_FILE="$SHADER_DIR/brightness.frag"

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

# Check if shader file exists, if not create with default brightness
if [ ! -f "$SHADER_FILE" ]; then
  CURRENT=1.0
else
  # Get current brightness multiplier
  CURRENT=$(grep -oP 'pixColor.rgb \*= \K[0-9.]+' "$SHADER_FILE" | tail -1)
fi

# Calculate new brightness (decrease by 10%)
NEW=$(echo "$CURRENT * 0.90" | bc -l)

# Cap at 0.1 to prevent complete darkness
if (( $(echo "$NEW < 0.1" | bc -l) )); then
  NEW=0.1
fi

# Format to 2 decimal places
NEW=$(printf "%.2f" "$NEW")

# Check if blue light filter is currently enabled
BLUELIGHT_ENABLED=false
if [ -f "$SHADER_FILE" ] && grep -q "pixColor.b \*= 0.6" "$SHADER_FILE"; then
  BLUELIGHT_ENABLED=true
fi

# Recreate the shader file
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_ENABLED" = true ]; then
  cat >> "$SHADER_FILE" << EOF
    // Reduce blue light
    pixColor.r *= 1.0;
    pixColor.g *= 0.85;
    pixColor.b *= 0.6;

EOF
fi

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

    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 "Brightness decreased from $CURRENT to $NEW"
