#!/bin/sh

# Wait for DBus session
while [ ! -S /run/user/$(id -u phablet)/bus ]; do
    sleep 1
done

export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u phablet)/bus

GLYPH_PATH="/sys/devices/platform/soc/984000.i2c/i2c-0/0-0020/leds/aw210xx_led"
ZONES="all_white_leds round_leds single_led rear_cam_led front_cam_led dot_led vline_leds"

turn_off_all() {
    for z in $ZONES; do
        echo "0" > "$GLYPH_PATH/${z}_br" 2>/dev/null
    done
}

show_pattern() {
    turn_off_all

    case $((RANDOM % 5)) in
        0)
            ZONE=$(echo $ZONES | tr ' ' '\n' | shuf -n1)
            echo "255" > "$GLYPH_PATH/${ZONE}_br"
            sleep 0.2
            echo "0" > "$GLYPH_PATH/${ZONE}_br"
            sleep 0.2
            echo "255" > "$GLYPH_PATH/${ZONE}_br"
            sleep 0.2
            echo "0" > "$GLYPH_PATH/${ZONE}_br"
            sleep 0.2
            echo "255" > "$GLYPH_PATH/${ZONE}_br"
            ;;
        1)
            ZONE1=$(echo $ZONES | tr ' ' '\n' | shuf -n1)
            ZONE2=$(echo $ZONES | tr ' ' '\n' | shuf -n1)
            for i in 1 2 3; do
                echo "255" > "$GLYPH_PATH/${ZONE1}_br"
                echo "255" > "$GLYPH_PATH/${ZONE2}_br"
                sleep 0.15
                echo "0" > "$GLYPH_PATH/${ZONE1}_br"
                echo "0" > "$GLYPH_PATH/${ZONE2}_br"
                sleep 0.15
            done
            echo "255" > "$GLYPH_PATH/${ZONE1}_br"
            echo "255" > "$GLYPH_PATH/${ZONE2}_br"
            ;;
        2)
            for i in 1 2 3; do
                for z in $ZONES; do
                    echo "255" > "$GLYPH_PATH/${z}_br"
                done
                sleep 0.1
                turn_off_all
                sleep 0.1
            done
            for z in $ZONES; do
                echo "255" > "$GLYPH_PATH/${z}_br"
            done
            ;;
        3)
            for i in 1 2 3; do
                echo "255" > "$GLYPH_PATH/rear_cam_led_br"
                echo "255" > "$GLYPH_PATH/front_cam_led_br"
                sleep 0.1
                echo "0" > "$GLYPH_PATH/rear_cam_led_br"
                echo "0" > "$GLYPH_PATH/front_cam_led_br"
                sleep 0.1
            done
            echo "255" > "$GLYPH_PATH/rear_cam_led_br"
            echo "255" > "$GLYPH_PATH/front_cam_led_br"
            ;;
        4)
            for i in 1 2 3; do
                echo "255" > "$GLYPH_PATH/round_leds_br"
                sleep 0.15
                echo "0" > "$GLYPH_PATH/round_leds_br"
                sleep 0.15
            done
            echo "255" > "$GLYPH_PATH/round_leds_br"
            ;;
    esac

    sleep 5
    turn_off_all
}

echo "Monitoring notifications..."

dbus-monitor "type='method_call',interface='org.freedesktop.Notifications',member='Notify'" |
grep --line-buffered "member=Notify" |
while read -r _; do
    show_pattern &
done
