#!/usr/bin/env bash
set -euo pipefail

# Samsung washing machine style "Die Forelle" jingle
# Requires: beep
#
# On many Linux systems beep needs permission to access the speaker.
# Example:
#   sudo modprobe pcspkr
#
# Run:
#   chmod +x samsung-forelle.sh
#   ./samsung-forelle.sh

BEEP_BIN="${BEEP_BIN:-beep}"

if ! command -v "$BEEP_BIN" >/dev/null 2>&1; then
  echo "Error: 'beep' is not installed." >&2
  exit 1
fi

# Tempo
BPM=132

# Derived note lengths in milliseconds
quarter=$((60000 / BPM))
eighth=$((quarter / 2))
half=$((quarter * 2))
dot_quarter=$((quarter + eighth))
sixteenth=$((quarter / 4))

# Slight separation between notes for that appliance-jingle articulation
gap=18

play() {
  local freq="$1"
  local dur="$2"
  local delay="${3:-$gap}"

  if [[ "$freq" -eq 0 ]]; then
    sleep "$(awk "BEGIN { printf \"%.3f\", $dur/1000 }")"
  else
    "$BEEP_BIN" -f "$freq" -l "$dur" -D "$delay"
  fi
}

# Equal-tempered pitches
C5=523
D5=587
E5=659
F5=698
G5=784
A5=880
B5=988
C6=1047
D6=1175
E6=1319

# Melody approximation of the Samsung "Die Forelle" washer tune
# Phrase 1
play $G5 $eighth
play $A5 $eighth
play $B5 $quarter
play $C6 $quarter
play $D6 $quarter
play $C6 $quarter
play $B5 $quarter
play $A5 $quarter

# Phrase 2
play $G5 $eighth
play $A5 $eighth
play $B5 $quarter
play $C6 $quarter
play $B5 $dot_quarter
play $A5 $eighth
play $G5 $half 40

# Phrase 3
play $B5 $eighth
play $C6 $eighth
play $D6 $quarter
play $E6 $quarter
play $D6 $quarter
play $C6 $quarter
play $B5 $quarter
play $A5 $quarter

# Ending
play $G5 $eighth
play $A5 $eighth
play $B5 $quarter
play $C6 $quarter
play $B5 $quarter
play $A5 $quarter
play $G5 $half 80