#!/usr/bin/env bash

# Exit immediately if a command exits with a non-zero status
set -e

echo "=== 1. Installing Fedora 44 Build Dependencies ==="
sudo dnf install -y \
  git \
  gcc-c++ \
  cmake \
  make \
  alsa-lib-devel \
  libvorbis-devel \
  libogg-devel \
  flac-devel \
  expat-devel \
  opus-devel \
  soxr-devel \
  avahi-devel \
  boost-devel

echo "=== 2. Cloning Snapcast Repository ==="
# Clone into a temporary directory
cd /tmp
if [ -d "snapcast" ]; then
    rm -rf snapcast
fi

# Clone main repo first, then sync submodules internally to prevent git syntax errors
git clone https://github.com/snapcast/snapcast
cd snapcast
git submodule update --init --recursive

echo "=== 3. Compiling Snapclient ==="
mkdir build && cd build
# BUILD_SERVER=OFF builds only the client application
cmake .. -DBUILD_SERVER=OFF
make -j$(nproc)

echo "=== 4. Installing Binary ==="
sudo make install
sudo cp /usr/local/bin/snapclient /usr/bin/snapclient

echo "=== 5. Setting Up Configuration File ==="
sudo mkdir -p /etc/default
if [ ! -f /etc/default/snapclient ]; then
    sudo tee /etc/default/snapclient > /dev/null << 'EOF'
# Start snapclient automatically?
START_SNAPCLIENT=true

# Additional options to pass to snapclient
# Change <IP_Address_of_your_Snapserver> to your actual server IP or hostname
SNAPCLIENT_OPTS="--host <IP_Address_of_your_Snapserver>"
EOF
    echo "Created template /etc/default/snapclient"
else
    echo "/etc/default/snapclient already exists. Skipping creation."
fi

echo "=== 6. Installing Systemd Service ==="
sudo tee /etc/systemd/system/snapclient.service > /dev/null << 'EOF'
[Unit]
Description=Snapcast client
Documentation=man:snapclient(1)
After=network.target sound.target

[Service]
EnvironmentFile=-/etc/default/snapclient
ExecStart=/usr/bin/snapclient $SNAPCLIENT_OPTS
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd to pick up the new service
sudo systemctl daemon-reload

echo "=========================================================="
echo " Setup Complete!"
echo "=========================================================="
echo "Next steps:"
echo "1. Edit /etc/default/snapclient to set your server's IP address:"
echo "   sudo nano /etc/default/snapclient"
echo ""
echo "2. Start and enable the service:"
echo "   sudo systemctl enable --now snapclient"
echo "=========================================================="

