#!/bin/bash
# Star Wars Theme Song - Buzzer Version
# Note: Buzzer can only be on/off, so we use timing patterns to create rhythm
# Volume is simulated at 10% by using very short pulse patterns (PWM-like effect)

BUZZER_PATH='/sys/class/leds/usr-buzzer/brightness'
DURATION=5  # Total duration in seconds

# Function to play a note with 10% volume effect
# Uses rapid on/off pulses to simulate lower volume
# $1 = note duration in hundredths of a second (e.g., 5 = 0.05s)
play_note() {
    local note_duration=$1
    # For 10% volume: 10ms on, 90ms off pattern
    # This creates a quieter, pulsing effect
    local cycles=$((note_duration * 2))  # Each cycle is ~50ms
    
    for i in $(seq 1 $cycles); do
        echo 1 | sudo tee $BUZZER_PATH > /dev/null 2>&1
        sleep 0.005  # 5ms on (10% duty cycle)
        echo 0 | sudo tee $BUZZER_PATH > /dev/null 2>&1
        sleep 0.045  # 45ms off
    done
}

# Function for silence/pause
pause() {
    local duration=$1
    sleep $duration
}

# Star Wars Theme Pattern
# Using timing to represent the iconic opening sequence
echo "Playing Star Wars Theme (5 seconds, 10% volume)..."
echo "=================================================="
echo ""

START_TIME=$(date +%s)

# Opening sequence (famous opening notes)
# Short-short-short-long pattern
play_note 2   # Very short
pause 0.05
play_note 2
pause 0.05
play_note 2
pause 0.1
play_note 4   # Longer
pause 0.1
play_note 6   # Even longer
pause 0.15

# Main theme rhythm - first phrase
play_note 3
pause 0.05
play_note 3
pause 0.05
play_note 3
pause 0.1
play_note 5
pause 0.1
play_note 4
pause 0.1
play_note 3
pause 0.1
play_note 5
pause 0.15

# Continue theme pattern - second phrase
play_note 4
pause 0.05
play_note 4
pause 0.05
play_note 4
pause 0.1
play_note 6
pause 0.1
play_note 5
pause 0.1
play_note 4
pause 0.1
play_note 6
pause 0.15

# Final sequence - third phrase
play_note 5
pause 0.05
play_note 5
pause 0.05
play_note 5
pause 0.1
play_note 8
pause 0.1
play_note 6
pause 0.1
play_note 5
pause 0.1
play_note 10
pause 0.2

# Fill remaining time to reach 5 seconds
CURRENT_TIME=$(date +%s)
ELAPSED=$((CURRENT_TIME - START_TIME))
REMAINING=$((DURATION - ELAPSED))

if [ $REMAINING -gt 0 ]; then
    # Continue theme pattern for remaining time
    while [ $(date +%s) -lt $((START_TIME + DURATION)) ]; do
        play_note 4
        pause 0.1
        play_note 5
        pause 0.1
        play_note 4
        pause 0.15
    done
fi

# Ensure buzzer is off
echo 0 | sudo tee $BUZZER_PATH > /dev/null 2>&1

echo ""
echo "Star Wars theme complete!"
