#!/usr/bin/env bash
#sudo curl -s -L https://bit.ly/multilarm-linux | bash
set -euo pipefail

echo "==================== Multilarm Installer ===================="

# Require root / sudo
if [[ $EUID -ne 0 ]]; then
    echo "Error: This script must be run with sudo."
    echo "Usage: sudo bash multilarminstall.sh"
    exit 1
fi

# Detect real user even when script is run with sudo
if [ -n "${SUDO_USER:-}" ]; then
    REAL_USER="$SUDO_USER"
else
    REAL_USER="$(whoami)"
fi

REAL_HOME=$(eval echo "~$REAL_USER")
ARCH=$(uname -m)

# Validate supported architecture
if [[ "$ARCH" != "aarch64" && "$ARCH" != "armv7l" && "$ARCH" != "armv6l" ]]; then
    echo "Error: Unsupported architecture '$ARCH'."
    echo "Multilarm supports: aarch64 (ARM64), armv7l/armv6l (ARM32)."
    exit 1
fi

echo "Installing for user: $REAL_USER"
echo "Home directory: $REAL_HOME"
echo "Architecture detected: $ARCH"

# 32-bit Pi OS notice. ARM32 (armv6l / armv7l) installs are fully featured —
# including Kokoro NEURAL TTS. ONNX Runtime publishes no 32-bit-ARM binary on
# nuget.org, so Multilarm ships a hand-cross-compiled libonnxruntime.so
# (ORT v1.26.0, armv7-a/NEON/hard-float; see ops/build-ort-arm32.sh) bundled
# into the linux-arm binary. The only caveat is SPEED: 32-bit ARM lacks the
# A64 NEON dot-product kernels (UDOT/SDOT) the quantised Kokoro model leans on,
# so inference is noticeably slower than on the 64-bit image, and 32-bit
# user-space caps process VAS ~3 GiB. Pi 4 / Pi 5 default to 64-bit Pi OS since
# 2023; the 32-bit image is mainly for Pi Zero / Pi 1 / Pi 2 v1.x.
if [[ "$ARCH" == "armv7l" || "$ARCH" == "armv6l" ]]; then
    echo ""
    echo "Notice: detected 32-bit ARM ($ARCH)."
    echo "        Multilarm is fully functional here, including Kokoro neural"
    echo "        TTS (via a bundled 32-bit ONNX Runtime). For FASTER neural"
    echo "        TTS, use the 64-bit Pi OS image (aarch64): expected 2-3x"
    echo "        speedup. https://www.raspberrypi.com/software/"
    echo ""
fi

# Multilarm ships as a SELF-CONTAINED single-file binary: the .NET runtime is
# bundled inside it, so there is no separate .NET install and no ICU dependency
# (globalisation runs in invariant mode). Runtime audio needs only ALSA
# (libasound2 — miniaudio dlopen()s libasound.so.2 at runtime). We also pull in
# the ALSA + PulseAudio command-line utils because the service's boot-time
# audio-wait helper probes them (pactl / aplay) to decide when an output device
# is live. wget/unzip fetch the binary and the sample resource bundle.
# We are already running as root (EUID check above), so no sudo prefix here.
echo "Installing required packages..."
apt-get update
apt-get install -y wget unzip libasound2 alsa-utils pulseaudio-utils

echo "Configuring environment variables..."

BASHRC="$REAL_HOME/.bashrc"
sudo -u "$REAL_USER" touch "$BASHRC"

add_bashrc_line() {
    grep -qxF "$1" "$BASHRC" || echo "$1" >> "$BASHRC"
}

# One variable the app relies on when launched from a login shell:
#   • invariant globalisation so .NET needs no ICU packages
# libmultilarm_audio.so resolves via /etc/ld.so.conf.d/multilarm_audio.conf +
# ldconfig (configured below), so no LD_LIBRARY_PATH export is needed here; the
# systemd unit sets its own LD_LIBRARY_PATH for the service launch path.
add_bashrc_line 'export DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1'

chown "$REAL_USER:$REAL_USER" "$BASHRC"

echo "Configuring system library path..."

LIBCONF="/etc/ld.so.conf.d/multilarm_audio.conf"

if ! grep -qxF "/usr/local/lib" "$LIBCONF" 2>/dev/null; then
    echo "/usr/local/lib" | tee "$LIBCONF" >/dev/null
fi

echo "Downloading Multilarm binaries..."

if [[ "$ARCH" == "aarch64" ]]; then
    BINARY_BASE="https://multilarm.com/multilarm/binaries/linux-arm64"
else
    BINARY_BASE="https://multilarm.com/multilarm/binaries/linux-arm"
fi

wget -q "$BINARY_BASE/Multilarm" -O "$REAL_HOME/Multilarm" || { echo "Error: Failed to download Multilarm binary."; exit 1; }

wget -q "$BINARY_BASE/libmultilarm_audio.so" -O "/usr/local/lib/libmultilarm_audio.so" || { echo "Error: Failed to download libmultilarm_audio.so."; exit 1; }

echo "Setting permissions..."

chown "$REAL_USER:$REAL_USER" "$REAL_HOME/Multilarm"
chmod 755 "$REAL_HOME/Multilarm"

chmod 755 /usr/local/lib/libmultilarm_audio.so

echo "Updating library cache..."
ldconfig

echo "Checking sample library..."

ADHAN_DIR="$REAL_HOME/Adhan"

if [[ -d "$ADHAN_DIR" ]]; then
    echo "Sample library already exists."
else
    echo "Downloading sample library..."

    sudo -u "$REAL_USER" wget -q https://multilarm.com/multilarm/binaries/SampleRes.zip -O "$REAL_HOME/SampleRes.zip" || { echo "Error: Failed to download sample library."; exit 1; }
    sudo -u "$REAL_USER" unzip -o "$REAL_HOME/SampleRes.zip" -d "$REAL_HOME"
    rm "$REAL_HOME/SampleRes.zip"
fi

echo "================ Installation Complete ================"
echo ""
echo "Please reboot the system."
echo ""
echo "After reboot run:"
echo "  $REAL_HOME/Multilarm"
