#!/bin/bash
# vim: et sts=4 sw=4

# Print the list of Nova stations

set -e
set -u

cmdcheck() { command -v "$1" >/dev/null 2>&1; }

assert_commands() {
    local missing=()
    local cmd=

    for cmd in "$@"; do
        cmdcheck $cmd || missing+=($cmd)
    done

    [ ${#missing[@]} -eq 0 ] && return 0

    echo "Missing command(s): ${missing[@]}" >&2
    echo "Please install it and retry." >&2
    exit 1
}

## main

assert_commands jq wget

URL=https://www.nova.fr/radios-data/www.nova.fr/all.json
FILTER_OUT="bordeaux|lyon"

ALL_JSON=$(wget -O- $URL)
STATIONS_JSON=$(echo "$ALL_JSON" | jq 'map({"radio"})')

# Go from JSON to plain text
STATIONS=$(echo "$STATIONS_JSON" | jq -r '.[].radio | "\(.id) \(.code) \(.stream_url) \(.name)"')
# Hack: rename 'Nouvo Nova' into 'Nova Nouvo' so that it sorts well
STATIONS=$(echo "$STATIONS" | sed 's/Nouvo Nova/Nova Nouvo/')
# Filter out some stations, remove duplicates, then sort per name
STATIONS=$(echo "$STATIONS" | grep -Ev " nova-($FILTER_OUT) " \
    | LC_ALL=C sort -u | sort -k4)

echo "-------- 8< --------"

while read -r id code url name; do
    #echo $id $code $url $name
    cat << EOF | sed -e 's/^/\t"/' -e 's/$/" \\/'
<Station>
  <name>${name}</name>
  <uri>${url}</uri>
</Station>
EOF
done <<< $STATIONS | sed '$ s/ \\$//'

echo "-------- >8 --------"
