#!/bin/sh
# Fetelabs SSJ2 mod: plays the Super Saiyan 2 power-up on the first login
# after each boot, and turns the task bar's water into a golden aura for
# exactly as long as it plays. Later logins in the same boot stay quiet.
#   fetelabs-ssj2-powerup          play if this is the boot's first login
#   fetelabs-ssj2-powerup --test   play now
#
# The shell plays the sound itself (ai.fetelabs.Water.PowerUp, from Water
# Panel or Fetelabs Task Bar), so the aura starts on the same frame as the
# sound. If no water is up, the sound plays on its own.
DATA="${XDG_DATA_HOME:-$HOME/.local/share}"
SOUND="$DATA/fetelabs-ssj2/ssj2-powerup.ogg"
ENVELOPE="${SOUND%.*}.aura.json"
MARK="${XDG_STATE_HOME:-$HOME/.local/state}/fetelabs-ssj2/powerup-boot"
BOOT=$(cat /proc/sys/kernel/random/boot_id)
EXT="$DATA/gnome-shell/extensions"
[ -f "$SOUND" ] || exit 0
if [ "$1" != "--test" ]; then
  [ "$(cat "$MARK" 2>/dev/null)" = "$BOOT" ] && exit 0
  mkdir -p "$(dirname "$MARK")" && echo "$BOOT" > "$MARK"
  # Give the sound server a moment to come up at login.
  i=0; while ! pactl info >/dev/null 2>&1 && [ $i -lt 20 ]; do sleep 0.5; i=$((i+1)); done
fi
# The aura's choreography, worked out from the sound (again if you swap the sound).
if [ ! -f "$ENVELOPE" ] || [ "$SOUND" -nt "$ENVELOPE" ]; then
  for tool in "$EXT/water-panel@fetelabs/aura-envelope.py" "$EXT/taskbar@fetelabs/water/aura-envelope.py"; do
    [ -f "$tool" ] && python3 -I "$tool" "$SOUND" "$ENVELOPE" >/dev/null 2>&1 && break
  done
fi
# The task bar may still be settling in: keep asking for up to 8 s.
i=0
while [ $i -lt 16 ]; do
  r=$(gdbus call --session --dest org.gnome.Shell --object-path /ai/fetelabs/Water \
        --method ai.fetelabs.Water.PowerUp "$SOUND" 2>/dev/null)
  case "$r" in "(true"*) exit 0 ;; esac
  sleep 0.5; i=$((i+1))
done
pw-play --media-role=Event "$SOUND" 2>/dev/null || paplay "$SOUND"
