#!/bin/bash
#####################################################
# PMRP                                              #
# Poor man's radio player                           #
# ==================================================#
# Internet radio streamer to listen to online radio #
# ==================================================#
# © 2025 WTFPL lxgator @ gmail.com                  # 
# ###################################################
ICON="/usr/share/icons/hicolor/48x48/apps/pmrp.png"
EICON="/usr/share/pmrp/icons/error.svg"
VERSION=1.0.9

# Kill it all if restarted
PID=`ps -eaf | grep record | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1 &
fi 
PID=`ps -eaf | grep streamripper | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1 &
fi 
PID=`ps -eaf | grep mpv | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1 &
fi 
PID=`ps -eaf | grep yad | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1 &
fi 
# Kill python scripts
pkill -f "PMRP" > /dev/null 2>&1
pkill -f "Record" > /dev/null 2>&1

# Need a network connection
wget -q --tries=3 --timeout=10 --delete-after "https://www.google.com/" 
if [ $? -eq 0 ]; then
  exec $@
else
$(yad --width=375 --height=100 --on-top --fixed --center --window-icon="$EICON" --image="$EICON" \
--title=Error --text="\nNo Network Connection\n\nCheck network or vpn failure?\nIgnore this message and continue?" \
--button="Cancel"!/usr/share/pmrp/icons/cancel.svg:"1" --button="OK"!/usr/share/pmrp/icons/ok.svg:"0") 
if [ $? = "1" ]; then
exit 0
 fi
  fi
# Test for mpv installed...
if [ $(which mpv) != "" ] 2>/dev/null ; then
exec
else
yad --width=350 --height=100 --window-icon="$EICON" --center --image="$EICON" \
--button="Cancel"!/usr/share/pmrp/icons/cancel.svg:1 --title=PMRP \
--text="\nPMRP requires 'mpv' but it's not installed!\nInstall 'mpv' to enjoy PMRP."
exit 0
fi
CONF="$HOME/.pmrp"
# New user, create defaulf folder, default stations file 
if ! test -d $CONF ; then
       mkdir -p $CONF
fi
# Add default stations on startup 
if ! test -f $CONF/stations ; then
`echo \
'## Stations
# Tag: "Name" "Category" "URL"
## internet-radio
Stream: "Classic Rock" "Rock" "http://144.217.158.59:5000/stream/1/"
Stream: "Smooth Jazz" "Jazz" "http://64.95.243.43:8002/stream/1/"
Stream: "EZ Hits" "Soft Rock" "http://airspectrum.cdnstream1.com:8018/1606_192"
Stream: "Easy 80s" "Soft Rock" "https://uk7.internet-radio.com/proxy/simonyates44?mp=/stream;"
Stream: "Hearthbeat FM" "Soft Rock" "http://cast5.magicstreams.gr:8010/listen.pls?sid=1"
Stream: "Box UK Radio" "Dance" "http://uk7.internet-radio.com:8226/stream"
Stream: "RadioSuperoldie" "Oldies" "http://87.118.87.46:8888/listen.pls?sid=1"
Stream: "Phoenix Country" "Country" "https://uk3.internet-radio.com/proxy/phoenixcr?mp=/live"
Stream: "SLRadio Country" "Country" "https://us1.internet-radio.com/proxy/slradio?mp=/stream;"
Stream: "Classic Rock Florida" "Rock" "http://144.217.158.59:5000/stream/1/"
Stream: "24-7 Motown" "Motown" "http://31.132.6.142:4237/stream/1/"
Stream: "Retro Hits" "Soft Rock" "http://149.56.183.178:8300/listen.pls?sid=1"
Stream: "Disco Classic Radio" "Disco" "http://54.36.89.71:8742/listen.pls?sid=1"
Stream: "1000 Smoothhits" "Soft" "https://1000smoothhits.stream.laut.fm/1000smoothhits"

## 181.FM
181.FM: "Jammin 181" "Urban" "http://relay.181.fm:8042"
181.FM: "Old School HipHop" "Urban" "http://relay.181.fm:8068"
181.FM: "The Beat" "Urban" "http://relay.181.fm:8054"
181.FM: "The Box" "Urban" "http://relay.181.fm:8024"
181.FM: "True R&B" "Urban" "http://relay.181.fm:8022"
181.FM: "Chilled Out" "Techno" "http://relay.181.fm:8700"
181.FM: "Energy 93" "Techno" "http://relay.181.fm:8044"
181.FM: "Energy 98" "Techno" "http://relay.181.fm:8800"
181.FM: "Studio 181" "Techno" "http://relay.181.fm:8072"
181.FM: "Techno Club" "Techno" "http://icyrelay.181.fm/181-technoclub_128k.mp3"
181.FM: "The Vibe of Vegas" "Techno" "http://relay.181.fm:8074"
181.FM: "80s Hairband" "Rock" "http://relay.181.fm:8014"
181.FM: "Chloe" "Rock" "http://relay.181.fm:8100"
181.FM: "Classic Buzz" "Rock" "http://relay.181.fm:8038"
181.FM: "Rock 181" "Rock" "http://relay.181.fm:8008"
181.FM: "Rock 40" "Rock" "http://relay.181.fm:8028"
181.FM: "The Buzz" "Rock" "http://relay.181.fm:8126"
181.FM: "The Eagle" "Rock" "http://relay.181.fm:8030"
181.FM: "The Rock" "Rock" "http://relay.181.fm:8064"
181.FM: "Party 181" "Pop" "http://relay.181.fm:8036"
181.FM: "Power 181" "Pop" "http://relay.181.fm:8128"
181.FM: "Smooth AC" "Pop" "http://relay.181.fm:8094"
181.FM: "The Heart" "Pop" "http://relay.181.fm:8006"
181.FM: "The Mix" "Pop" "http://relay.181.fm:8032"
181.FM: "The Office" "Pop" "http://relay.181.fm:8002"
181.FM: "The Point" "Pop" "http://relay.181.fm:8010"
181.FM: "UK Top 40" "Pop" "http://relay.181.fm:8070"
181.FM: "Beatles" "Oldies" "http://relay.181.fm:8062"
181.FM: "Classic Hits" "Oldies" "http://relay.181.fm:8132"
181.FM: "Good Time Oldies" "Oldies" "http://relay.181.fm:8046"
181.FM: "Mellow Gold" "Oldies" "http://relay.181.fm:8060"
181.FM: "Soul" "Oldies" "http://relay.181.fm:8058"
181.FM: "Super 70s" "Oldies" "http://relay.181.fm:8066"
181.FM: "Reggae Roots" "Latin" "http://relay.181.fm:8096"
181.FM: "Salsa" "Latin" "http://relay.181.fm:8098"
181.FM: "Acid Jazz" "Easy" "http://icyrelay.181.fm/181-acidjazz_128k.mp3"
181.FM: "Bebop" "Easy" "http://icyrelay.181.fm/181-bebop_128k.mp3"
181.FM: "Classical Guitar" "Easy" "http://icyrelay.181.fm/181-classicalguitar_128k.mp3"
181.FM: "Classical Jazz" "Easy" "http://icyrelay.181.fm/181-classicaljazz_128k.mp3"
181.FM: "Classical Music" "Easy" "http://icyrelay.181.fm/181-classical_128k.mp3"
181.FM: "Fusion Jazz" "Easy" "http://icyrelay.181.fm/181-fusionjazz_128k.mp3"
181.FM: "Sensual World" "Easy" "http://icyrelay.181.fm/181-sensual_128k.mp3"
181.FM: "The Breeze" "Easy" "http://relay.181.fm:8004"
181.FM: "Trance Jazz" "Easy" "http://icyrelay.181.fm/181-trancejazz_128k.mp3"
181.FM: "True Blues" "Easy" "http://icyrelay.181.fm/181-blues_128k.mp3"
181.FM: "Vocal Jazz" "Easy" "http://icyrelay.181.fm/181-vocals_128k.mp3"
181.FM: "Front Porch" "Country" "http://relay.181.fm:8016"
181.FM: "Highway 181" "Country" "http://relay.181.fm:8018"
181.FM: "Kickin Country" "Country" "http://relay.181.fm:8130"
181.FM: "Real Country" "Country" "http://relay.181.fm:8034"
181.FM: "US 181" "Country" "http://relay.181.fm:8056"
181.FM: "Comedy Club" "Comedy" "http://relay.181.fm:8026"
181.FM: "90s Alternative" "90s" "http://relay.181.fm:8052"
181.FM: "90s Country" "90s" "http://relay.181.fm:8050"
181.FM: "90s Dance" "90s" "http://relay.181.fm:8140"
181.FM: "Lite 90s" "90s" "http://relay.181.fm:8048"
181.FM: "Star 90s" "90s" "http://relay.181.fm:8012"
181.FM: "80s Country" "80s" "http://relay.181.fm:8134"
181.FM: "Awesome 80s" "80s" "http://relay.181.fm:8000"
181.FM: "Lite 80s" "80s" "http://relay.181.fm:8040"

## Blues
Blues: "Top Blues" "Blues" "https://us3.internet-radio.com/proxy/topblues?mp=/stream"
Blues: "Blues Radio" "Blues" "http://i4.streams.ovh:8352/;stream/1"

## Favorites 
Favorites: "Add your" "favorite" "stations here"
Favorites:
Favorites:
Favorites:
Favorites:
Favorites:' \
| awk '{print $0}' > $CONF/stations`
fi
#Creat a edit/add menu
if ! test -f $CONF/edit ; then
`echo \
'#!/bin/bash
CONF="$HOME/.pmrp"
EDIT=$(yad --center --text-info --editable --filename="$CONF/stations" --title=Stations --window-icon=/usr/share/icons/hicolor/48x48/apps/pmrp.png --width=650 --height=500 --button="Help"!/usr/share/pmrp/icons/help.svg:5 --button="Cancel"!/usr/share/pmrp/icons/cancel.svg:1 --button="Save"!/usr/share/pmrp/icons/save.svg:0)
ret=$?
if [ $ret -eq 0 ]; then
echo "$EDIT" | awk {print} > $CONF/tmp 
mv $CONF/tmp $CONF/stations
fi 
if [ $ret -eq 5 ]; then
$(yad --center --text="Favorites:  Name Category URL\n\nAdding your favorite urls is fairly simple but must be entered correctly in order to function properly\n\nStations name genre url must be in quotes. See layout in the default urls" --title="Information" --window-icon=/usr/share/icons/hicolor/48x48/apps/pmrp.png --width=450 --height=150 --fixed --button="Cancel"!/usr/share/pmrp/icons/cancel.svg:1)
exec "$HOME/.pmrp/edit"
fi' | awk '{print $0}' > $CONF/edit`
chmod a+x $CONF/edit
fi

# remove and clean out on restart
rm -f $HOME/.pmrp/{p*,c*,P*} 2>/dev/null

TEXTDOMAIN=ydesk
TEXTDOMAINDIR=/usr/share/locale

export LANG=C.UTF-8
export pmrp='@bash -c "run_stations %2"'
export pmrp_stations=$HOME/.pmrp/stations
export ppipe=$(mktemp -u $HOME/.pmrp/ppmrp.XXXXXXXX)
export fpipe=$(mktemp -u $HOME/.pmrp/pmrp.XXXXXXXX)
export cpipe=$(mktemp -u $HOME/.pmrp/cpmrp.XXXXXXXX)
export statuspipe=$(mktemp -u $HOME/.pmrp/cpmrp.XXXXXXXX)
export PMRPLIST=$(mktemp -u $HOME/.pmrp/PMRPLIST.XXXXXXXX)

# Pipe for setting values in the form tab
mkfifo "$fpipe"
# control pipe - send commands to mpv
mkfifo "$cpipe"
# status pipe - send text to left text pane
mkfifo "$statuspipe"

# Create the list file
> $PMRPLIST

#File to store default category

export CAT_FILE=$(mktemp -u $HOME/.pmrp/pmrpcat.XXXXXXXX)
> $CAT_FILE

trap "rm -f $fpipe $cpipe $statuspipe $PMRPLIST $CAT_FILE" EXIT

pmkey=$(($RANDOM * $$))

# Categories are separated with "!" (without quotes)
# The last item in category is without trailing "!"
Categories="Stream!181.FM!Blues!Favorites"

function stations
{
   if [[ "$1" != "$CAT_DEFAULT" ]]; then
      echo "Category: $1" >> "$ppipe"
   fi
   < "$pmrp_stations" sed -n -e 's/^.*'"$1: "'//p' \
   | sed -e $'s/\" \"/\\\n/g;s/\"//g' >> "$fpipe"
}
export -f stations

function run_stations
{
    echo "3:@disabled@"
    echo -e '\f' >> "$fpipe"

    echo "$1" > "$CAT_FILE"

    case "$1" in
	Stream)
          stations "$1"
	    ;;
	181.FM)
          stations "$1"
	    ;;
	Blues)
          stations "$1"
	    ;;
	Favorites)
          stations "$1"
	    ;;
         *)
          echo "PMRP: Error! No such Category $1" >> "$ppipe"
            ;;
    esac
    echo "3:$pmrp"
}
export -f run_stations

function load_url
{
    echo "Station: $1   Url: $3" >> $ppipe    
    # Station to the list
    echo "$3" > $PMRPLIST
    # Unload current Playlist
    echo "playlist_remove current" > $cpipe
    # Load list
    echo "loadlist $PMRPLIST" > $cpipe
}
export -f load_url

function status_block
{
if [[ ! -z "$PMRP" ]]; then
   unset PMRP
else
  if [[ "$(echo "$1" | grep -c "^Name*")" = 1 ]]; then
      STATION="$1"
  elif [[ "$(echo "$1" | grep -c "^Title*")" = 1 ]];then
      TITLE="$1"
      date +"Time: %T" >> $ppipe
  elif [[ "$(echo "$1" | grep -c "^Bitrate")" = 1 ]];then
      BITRATE="$1 Kb/s"
  elif [[ "$(echo "$1" | grep -c "^PMRP:*")" = 1 ]];then
      PMRP="$1"
  fi
  
  if [[ -z "$PMRP" ]]; then
    echo "$STATION\n$BITRATE\n$TITLE" >> "$statuspipe"
  else
    echo "\n$PMRP\n" >> "$statuspipe"
  fi
  
  CAT_DEFAULT="$(cat $CAT_FILE)"

  if [[ "$CAT_DEFAULT" == "" ]]; then
     CAT_DEFAULT="181.FM" 
  fi

   echo "$(for category in $Categories
           do
             if [[ "$category" == "$CAT_DEFAULT" ]]; then
                printf "^%s" "$CAT_DEFAULT" 
             elif [[ "$category" != "$CAT_DEFAULT!" ]]; then
                printf "%s" "$category" 
             else
                printf "^%s!" "$CAT_DEFAULT" 
             fi
           done
          )" >> "$statuspipe"
   echo "$pmrp" >> "$statuspipe" 
fi
}

exec 3<> $fpipe 2>/dev/null
exec 4<> $ppipe 2>/dev/null
exec 5<> $cpipe 2>/dev/null
exec 6<> $statuspipe 2>/dev/null
echo "  Ready to Play" >> "$ppipe" 2>/dev/null
PID=`ps -eaf | grep mpv | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1 |less
fi 
function main() {
  yad --plug="$pmkey" --tabnum=1 --form --cycle-read --field "Select Category and Load Stations":FBTN --field "Category":CB  \
     --image-ontop --field="Load Stations"!/usr/share/pmrp/icons/add.svg:fbtn <&6 & 
     
  yad --plug="$pmkey" --tabnum=2 --list --no-markup --dclick-action="mpv --no-cache ${load_url}" > $HOME/.pmrp/playing  \
    --text "Double click to play" --text-align=center --column="Name" --column="Category" --column="Url" \
    --search-column=1 --expand-column=1 --print-column="3" <&3 &

  # loads fields on startup
  status_block ""

  # Reprints metadata after returning from tray
  echo 'print_text ${metadata}' > $cpipe
 yad --paned --key="$pmkey" --button="Stop!/usr/share/pmrp/icons/stop.png!Stop Playing Stream":'pkill -SIGKILL mpv' &>/dev/null  \
 yad --paned --key="$pmkey" --button="Tray!/usr/share/pmrp/icons/radio.png!Close to Menu Tray":1 \
 yad --paned --key="$pmkey" --button="Add Url"!/usr/share/pmrp/icons/add.svg!"Add New Url":"$HOME/.pmrp/edit" \
      --button="Quit!/usr/share/pmrp/icons/stop.svg!Quit Player":4 --text="\nPMRP: Poor Man's Radio Player\n\n               <span color=\"#BE7F00\"><b>Use the Stop button before changing to a new radio station</b></span>" --width=700 --height=500 \
        --title=$"PMRP" --splitter=300 --window-icon="/usr/share/icons/hicolor/48x48/apps/pmrp.png" --orient=hor --image="/usr/share/icons/hicolor/48x48/apps/pmrp.png" --image-on-top --center --posx=100 --posy=100 
# <span color=\"#BE7F00\"><b>Use the Stop button before changing to a new radio station</b></span>
RET="$?"
if [[ $RET -eq 4 ]]; then
PID=`ps -eaf | grep streamripper | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1 
fi &
PID=`ps -eaf | grep mpv | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1 |less
fi &
PID=`ps -eaf | grep pmrp | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1 |less
fi 
  fi
if [[ $RET -eq 7 ]]; then
run_stations "$(cat $CAT_FILE)" &>/dev/null 
       status_block ""
main
else
exec
fi 
case $RET in
  252)
    echo "quit" >> $cpipe
    echo "PMRP: Preparing for radio silence" >> "$ppipe"
    echo "PMRP: Zzzzzzz" >> "$ppipe"
    ;;
    1) 
if [ $? = 0 ]; then
while true; do
cat $HOME/.pmrp/pmrpcat.* > $HOME/.pmrp/current;
grep -E "http://" $HOME/.pmrp/playing | sed 's/[^ ]* //'|sed '2d' > $HOME/.pmrp/url;
grep -E "icy-title" $HOME/.pmrp/playing| sed 's/^............//'| sed 's/(.*//'| sed 's/[[].*//'| tail -n1 >> $HOME/.pmrp/current;
sleep 2;
done
fi & 
python3 /usr/share/pmrp/notify/PMRP

run_stations "$(cat $CAT_FILE)" &>/dev/null
       status_block ""
main
   ;;
   *) exit 1

    ;;
esac
}
main


exec 3>&-
exec 4>&-
exec 5>&-
exec 6>&-

