#!/usr/bin/env bash

echo "Preparing hyprlock configuration..."
# Path to hyprlock configuration file
CONF="$HOME/.config/hypr/hyprlock.conf"
# Get the list of outputs
mapfile -t outputs < <(hyprctl -j monitors | jq -r '.[].name')

# Generate the background blocks for each output
block=""
for output in "${outputs[@]}"; do
  block+=$'background {\n'
  block+=$"    monitor = ${output}\n"
  block+=$"    path = screenshot\n"
  block+=$"    reload_time = 0\n"
  block+=$"    reload_cmd = echo \"/tmp/${output}-lockscreen.png\"\n"
  block+=$"    crossfade_time = 1\n"
  block+=$'}\n\n'
done
# Insert the generated blocks into the configuration file
awk -v content="$block" '
  /^# AUTO BACKGROUND$/ { print; print content; inside=1; next }
  inside && /^# AUTO BACKGROUND END$/ { print; inside=0; next }
  inside { next }
  { print }
' "$CONF" > "${CONF}.tmp" && mv "${CONF}.tmp" "$CONF"

echo "Starting hyprlock..."
/home/nathan/Git/hyprlock/build/hyprlock &

echo "Taking screenshots for lock screen..."
# Take a screenshot of each output before locking (!THIS IS SLOW!)
for output in "${outputs[@]}"; do
    # grim -o "$output" "/tmp/${output}-lockscreen.png" &
    $HOME/.config/hypr/scripts/spots.sh -s 8 <(grim -o "$output" -) "/tmp/${output}-lockscreen.png" &
done

echo "Waiting for screenshots to complete..."
# Wait for all image processing to complete
while pgrep -x spots.sh >/dev/null; do
    sleep 0.1
done
# Notify hyprlock to reload backgrounds
echo "Reloading hyprlock backgrounds..."
pkill -USR2 hyprlock

echo "Waiting for hyprlock to exit..."
wait

echo "Hyprlock exited. Cleaning up..."
# Cleanup: Restore hyprlock.conf to original state
sed -i '/^# AUTO BACKGROUND$/,/^# AUTO BACKGROUND END$/{//!d}' "$CONF"

# Remove the screenshots
for output in "${outputs[@]}"; do
    rm "/tmp/${output}-lockscreen.png"
done
