#!/bin/sh set -u base=/data/opt/alice-backend runtime="$base/spotify" cd "$base" || exit 1 umask 077 exec 8>/tmp/alice-spotify.lock flock -n 8 || exit 1 export PULSE_SERVER=unix:/tmp/alice-pulse/native export PULSE_RUNTIME_PATH=/tmp/alice-pulse export PULSE_COOKIE=/tmp/alice-pulse/cookie export PULSE_STATE_PATH="$base/spotify-state" export PULSE_SINK=music pulse= soloist= janitor= timer= stopping=0 terminate() { stopping=1 for child in "$timer" "$soloist" "$pulse" "$janitor"; do [ -z "$child" ] || kill -TERM "$child" 2>/dev/null || true done } trap terminate TERM INT HUP trap terminate EXIT mkdir -p "$PULSE_RUNTIME_PATH" "$PULSE_STATE_PATH" "$base/soloist-data" /tmp/alice-spotify-cache if ! grep -q ' /tmp/alice-spotify-cache ' /proc/mounts; then mount -t tmpfs -o size=32m,mode=0700,nosuid,nodev,noexec tmpfs /tmp/alice-spotify-cache || exit 1 fi chmod 700 "$PULSE_RUNTIME_PATH" "$PULSE_STATE_PATH" "$base/soloist-data" /tmp/alice-spotify-cache if [ ! -f "$PULSE_COOKIE" ]; then dd if=/dev/urandom of="$PULSE_COOKIE" bs=256 count=1 2>/dev/null; fi : >/tmp/alice-cache.log ./music-control -cache-janitor /tmp/alice-spotify-cache >>/tmp/alice-cache.log 2>&1 8>&- & janitor=$! bound_logs() { for log in /tmp/alice-pulse.log /tmp/alice-soloist.log /tmp/alice-cache.log; do if [ -f "$log" ] && [ "$(wc -c < "$log")" -gt 524288 ]; then : > "$log"; fi done } # Session restoration requires network and wall time valid for TLS. while [ "$stopping" -eq 0 ] && { [ "$(date +%s)" -lt 1700000000 ] || ! ip route | grep -q '^default '; }; do sleep 3 & timer=$!; wait "$timer" || true; timer= done while [ "$stopping" -eq 0 ]; do : >/tmp/alice-pulse.log "$runtime/run" "$runtime/bin/pulseaudio" -n --daemonize=no --exit-idle-time=-1 --dl-search-path="$runtime/lib" --file="$runtime/etc/alice.pa" --log-target=stderr >>/tmp/alice-pulse.log 2>&1 8>&- & pulse=$! ready=0 for second in 1 2 3 4 5; do [ "$stopping" -eq 0 ] || break if "$runtime/pactl" info >/dev/null 2>&1; then ready=1; break; fi sleep 1 done if [ "$ready" -eq 1 ] && [ "$stopping" -eq 0 ]; then : >/tmp/alice-soloist.log "$runtime/run" "$runtime/soloist/soloist" --device-name "Pepega Mini 2" --api-key "$(cat "$base/soloist-key")" --data-dir "$base/soloist-data" --cache-dir /tmp/alice-spotify-cache --cache-size 100 --ws 127.0.0.1:9090 >>/tmp/alice-soloist.log 2>&1 8>&- & soloist=$! while [ "$stopping" -eq 0 ] && kill -0 "$soloist" 2>/dev/null && kill -0 "$pulse" 2>/dev/null; do bound_logs sleep 3 & timer=$!; wait "$timer" || true; timer= done fi for child in "$soloist" "$pulse"; do if [ -n "$child" ]; then kill -TERM "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; fi done soloist= pulse= bound_logs if [ "$stopping" -eq 0 ]; then sleep 5 & timer=$!; wait "$timer" || true; timer=; fi done [ -z "$janitor" ] || wait "$janitor" 2>/dev/null || true umount /tmp/alice-spotify-cache || true