#!/usr/bin/env sh # -*- sh -*- : "${RADIO_STATIONS:=${XDG_CONFIG_HOME:-$HOME/.config}/radio/stations}" : "${RADIO_PLAYER:=$(command -v mpv 2>/dev/null)}" _radio_url=1 _radio_desc=2 _radio_tags=3 RADIO_PID_FILE=/tmp/radio.pid RADIO_STATUS_FILE=/tmp/radio.status usage() { cat <&2 "Option -$OPTARG requires an argument" exit 1 ;; esac ;; \?) echo >&2 "Uknown option: -$OPTARG" exit 1 ;; esac done shift $((OPTIND - 1)) _radio_play "$@" } _radio_status() { trap 'echo;exit 0' INT if [ "x$1" = x-f ]; then follow=-f else follow= fi tail $follow "$RADIO_STATUS_FILE" echo exit } _radio_play() { candidates="$(sed -e 1d -e '/^#/d' "$RADIO_STATIONS" | grep -i "$1")" if [ -z "$candidates" ]; then candidates="$(sed -e 1d -e '/^#/d' "$RADIO_STATIONS")" fi if [ "$(printf '%s\n' "$candidates" | wc -l)" -gt 1 ]; then printf '%s\n' "$candidates" | cut -f $_radio_desc | cat -n - read -p "Radio> " radio if ! (echo "$radio" | grep -qE '^[0-9]+$'); then exit 1 fi station="$(printf '%s\n' "$candidates" | head -n "$radio" | tail -n 1)" else station="$candidates" fi echo "$station" | cut -f $_radio_desc >/tmp/radio.last_played if [ -f "$RADIO_PID_FILE" ]; then _radio_kill_impl fi echo >&2 "Playing $(echo "$station" | cut -f $_radio_desc)..." "$RADIO_PLAYER" "$(echo "$station" | cut -f $_radio_url)" >"$RADIO_STATUS_FILE" 2>&1 & echo $! >"$RADIO_PID_FILE" exit } _radio_kill_impl() { while xargs -a "$RADIO_PID_FILE" kill 2>/dev/null; do printf '.' done } _radio_kill() { if ! [ -f "$RADIO_PID_FILE" ]; then echo >&2 "I don't think radio is running." exit 1 fi printf >&2 '%s' "Killing radio" _radio_kill_impl rm "$RADIO_PID_FILE" echo exit } _radio_edit() { exec $EDITOR "$RADIO_STATIONS" } _radio_list() { sed 1d "$RADIO_STATIONS" | grep "$1" | awk ' BEGIN { FS="\t"; } $0 !~ /^#/ { descstr = $'$_radio_desc'; urlstr = $'$_radio_url'; tagstr = $'$_radio_tags'; printf "%-23s\t", substr(descstr,1,20) (length(descstr)>20?"...":""); printf "%-23s\t", substr(tagstr,1,20) (length(tagstr)>20?"...":""); printf "%-23s\n", substr(urlstr,1,20) (length(urlstr)>20?"...":""); }' exit } main "$@"