#!/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 values
if [ ! -f "$SHADER_FILE" ]; then
  CURRENT_BRIGHTNESS=1.0
  BLUELIGHT_ENABLED=false
else
  # Get current brightness multiplier
  CURRENT_BRIGHTNESS=$(grep -oP 'pixColor.rgb \*= \K[0-9.]+' "$SHADER_FILE" | tail -1)

  # Check current state by looking at the blue channel multiplier
  if grep -q "pixColor.b \*= 0.6" "$SHADER_FILE"; then
    BLUELIGHT_ENABLED=true
  else
    BLUELIGHT_ENABLED=false
  fi
fi

# Toggle the blue light filter state
if [ "$BLUELIGHT_ENABLED" = true ]; then
  # Filter is ON, turn it OFF
  NEW_STATE=false
  echo "Blue light filter: OFF"
else
  # Filter is OFF, turn it ON
  NEW_STATE=true
  echo "Blue light filter: ON"
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 [ "$NEW_STATE" = 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 *= $CURRENT_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"
