#!/bin/sh

init_variables() {
  progname=${0##*/}

  CHANNELS_URL='https://api.somafm.com/channels.json'
  CACHE_CHANNELS_FILE="${XDG_CACHE_HOME:-${HOME}/.cache}/somafm_channels.json"

  action=
  channel_id=
}

parse_command_line() {
  action="$1"
  channel_id="$2"
}

validate_command_line() {
  if [ -z "${action}" ]; then
    exit_error "missing action argument"
  fi

  if [ "${action}" != "channels" ] && [ "${action}" != "playlist" ] \
    && [ "${action}" != "direct_url" ]; then
    exit_error "invalid action ${action}"
  fi

  if { [ "${action}" = "playlist" ] || [ "${action}" = "direct_url" ]; } \
    && [ -z "${channel_id}" ]; then
    exit_error 'missing channel argument'
  fi
}

exit_error() {
  [ -z "$1" ] || echo "${progname}: $1"
  exit 1
} >&2

should_build_cache() {
  [ -f "${CACHE_CHANNELS_FILE}" ] || return 0

  cache_last_modified=$(stat -c '%Y' "${CACHE_CHANNELS_FILE}")
  current_time=$(date +%s)

  # keep cache for one week
  [ $((current_time - cache_last_modified)) -gt 604800 ]
}

build_cache() {
  mkdir -p "$(dirname "${CACHE_CHANNELS_FILE}")"

  echo "Fetching list of channels..." >&2
  curl -s "${CHANNELS_URL}" -o "${CACHE_CHANNELS_FILE}"
}

somafm_channels() {
  jq -r '.channels[]
         | [ .id, .title, .dj, .genre, .description ]
         | @tsv' \
    "${CACHE_CHANNELS_FILE}"
}

somafm_playlist() {
  # select highest quality stream preferably in AAC format
  jq -r ".channels[]
         | select(.id==\"${channel_id}\")
         | .playlists[]
         | [ .quality, .format, .url ]
         | @tsv" \
    "${CACHE_CHANNELS_FILE}" \
    | sed '{
        s/^highest/1/
        s/^high/2/
        s/^low/3/
        s/\taacp/\t2/
        s/\taac/\t1/
        s/\tmp3/\t3/
      }' \
    | sort -k 1,2 \
    | head -n 1 \
    | cut -f 3
}

somafm_direct_url() {
  echo "Fetching channel..." >&2
  # shellcheck disable=SC2312
  curl -s "$(somafm_playlist)" \
    | sed -n 's/^File1=\(.*\)/\1/p'
}

init_variables
parse_command_line "$@"
validate_command_line

should_build_cache && build_cache

"somafm_${action}"
