#!/usr/bin/env bash
# Tiny Radio terminal player installer.
#   curl -fsSL https://tinyradio.net/install | bash
# Puts the `tinyradio` script in a folder you can write to, makes sure that folder
# is on your PATH, and tells you if you still need an audio player.

set -eu

SCRIPT_URL="https://tinyradio.net/tinyradio"

# 1. pick a destination: /usr/local/bin if writable, else ~/.local/bin
if [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
  DEST=/usr/local/bin
else
  DEST="$HOME/.local/bin"
  mkdir -p "$DEST"
fi

# 2. download
TMP=$(mktemp)
curl -fsSL "$SCRIPT_URL" -o "$TMP"
head -1 "$TMP" | grep -q bash || { echo "Download did not look like the tinyradio script. Try again in a minute." >&2; exit 1; }
install -m 755 "$TMP" "$DEST/tinyradio"
rm -f "$TMP"
echo "Installed: $DEST/tinyradio"

# 3. PATH
case ":$PATH:" in
  *":$DEST:"*) ;;
  *)
    SHELL_NAME=$(basename "${SHELL:-bash}")
    case "$SHELL_NAME" in
      zsh)  RC="$HOME/.zshrc" ;;
      bash) RC="$HOME/.bashrc"; [ "$(uname)" = Darwin ] && RC="$HOME/.bash_profile" ;;
      fish) RC="" ;;
      *)    RC="$HOME/.profile" ;;
    esac
    if [ -n "$RC" ]; then
      if ! grep -qs "$DEST" "$RC"; then
        printf '\n# Tiny Radio terminal player\nexport PATH="%s:$PATH"\n' "$DEST" >> "$RC"
      fi
      echo "Added $DEST to your PATH in $RC. Open a new terminal tab, or run:"
      echo "    export PATH=\"$DEST:\$PATH\""
    else
      echo "Add $DEST to your PATH, then open a new terminal tab."
    fi
    ;;
esac

# 4. audio player
PLAYER=""
for p in mpv ffplay vlc cvlc; do command -v "$p" >/dev/null 2>&1 && { PLAYER=$p; break; }; done
if [ -n "$PLAYER" ]; then
  echo "Audio player found: $PLAYER"
  echo
  echo "Now type:  tinyradio"
else
  echo
  echo "You need one audio player. Any of these works; mpv is the nicest but takes a few minutes to install on a Mac:"
  if command -v brew >/dev/null 2>&1; then
    echo "    brew install mpv"
  elif command -v apt-get >/dev/null 2>&1; then
    echo "    sudo apt install mpv"
  else
    echo "    install mpv, ffmpeg or VLC with your package manager"
  fi
  echo "Then type:  tinyradio"
fi
