#!/usr/bin/env bash
#----------------------------------------------------------------------------
# Customize these vars to fit your env
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
RED='\033[0;31m'
YEL='\033[1;33m'
BRed='\033[1;31m'         # Red bold
BGreen='\033[1;32m' 
NC='\033[0m' 					# No Color
ResProtocols="http rtmp rtsp"  # Set your restreaming protocol priority order
Remonitor=1
Hold='-hold'
MonWait=12      # Buffering time before starting the restream monitor
MonPlayers='ffplay mpv'

#-----------------------------------------------------------------------------

OS=$OSTYPE                                    # Test your OS 
case "$OS" in 
"linux-gnu") 
 LocalIp=$(ip route | grep -om 1 'src.*' | cut -d ' ' -f2)
 OsType=0;;
 #LocalIp=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')
*"bsd"*)
 LocalIp=$(ifconfig | grep inet | grep netmask | grep broadcast | head -1 | cut -d ' ' -f2)
 OsType=1;;
 *"darwin"*)
  LocalIp=$(ifconfig | grep inet | grep netmask | grep broadcast | head -1 | cut -d ' ' -f2)
OsType=2
vlcapp="/Applications/VLC.app/Contents/MacOS/VLC";;
esac
#---------------------------------------------------------------------------
function ctrl_c () {
    clear
    kill -9 $ResPid 2>/dev/null
    kill -9 $MonPid 2>/dev/null
    exit
}
trap ctrl_c INT
#------------------------------------------------------------------------------------------

for MonPlayer in $MonPlayers; do
	if [ -n "`which $MonPlayer 2>/dev/null`" ]; then
	break
fi
done

#----------------------------------------------------------------------------

Restream () {
 
    ResClean 
   Re=$(echo "$VideoLink" | grep -c http)
    if [ "$Re" = "1" ]; then
        Re=""
    else
        Re="-re"
    fi
    
       if [ "$ResProt" = "rtsp" ]; then
        if [ "$OsType" =  "2" ]; then
          cmd_to_run="ffmpeg  $Re -stream_loop -1 -i '$VideoLink' -vcodec libx264 -acodec aac -f rtsp $Target"
          osascript -e "tell application \"Terminal\" to do script \"$cmd_to_run\"activate" &
         else
        xterm $Hold -iconic -e "ffmpeg  $Re -stream_loop -1 -i '"$VideoLink"' -vcodec libx264 -acodec aac -f rtsp $Target"  &
       
       fi   
          ResPid="$!"
        disown
      fi
       
      if [ "$ResProt" = "rtmp" ]; then
       if [ "$OsType" = "2" ]; then
      cmd_to_run="ffmpeg $Re -i '$VideoLink' -vcodec libx264 -vprofile baseline -acodec aac -strict -2 -f flv  $Target"
      osascript -e "tell application \"Terminal\" to do script \"$cmd_to_run\"activate" &
      else
         xterm $Hold -iconic -e "ffmpeg $Re -i '"$VideoLink"' -vcodec libx264 -vprofile baseline -acodec aac -strict -2 -f flv  $Target" &
      fi
        ResPid="$!"
        disown
      fi
      
      if [ "$ResProt" = "http" ]; then
     if [ "$OsType" = "2" ]; then
     cmd_to_run="ffmpeg $Re -i '$VideoLink' -c copy -f mpegts - | '$vlcapp' -I dummy -q --volume-step=10 - --sout '#standard{access=http,mux=ts,dst=$LocalIp:8530}'"
     osascript -e "tell application \"Terminal\" to do script \"$cmd_to_run\"activate" &
      else
      xterm -iconic $Hold  -e "ffmpeg $Re -i  '$VideoLink' -c copy  -f mpegts - | vlc -I dummy -q --volume-step=10 - --sout '#standard{access=http,mux=ts,dst=$LocalIp:8530}'"  &
       fi
        ResPid="$!"
        disown
    fi
   dialog  --title "Restreaming" --infobox "Your link is being restreamed locally on $Target" 5 40
    
     ResCheck
  }  
  
#-----------------------------------------------------------------------------------------

ResCheck () {
    ReCheck=0
    IsStreaming="00"
    if [ "$Remonitor" = "1" ]; then
        while [ 1 ]; do
            let ReCheck++
            sleep 3
            if [ "$OsType" = "1" ]; then
            IsStreaming=$(ps -af | grep -E "$LocalIp|239.101.101.1" | grep  "$ResPid")
            else
          IsStreaming=$(ps -ef | grep -E "$LocalIp|239.101.101.1" | grep  "$ResPid") 
          fi  
               if [ "$IsStreaming" != "00" ]; then
                ResMon
                return
            fi
            if [ "$ReCheck" = "10" ]; then
                dialog  --title "Restreaming failed" --infobox "$ChName failed to be restreamed on \n$Target\n\nCheck the Terminal for details." 10 45
                sleep 2
                return
            fi
         done
    fi
}

#--------------------------------------------------------------------------

ResClean () {
    ResProt=$(echo "$ResProtocols" | cut -d " " -f1)
    if [ "$ResProt" = "http" ]; then
        Target="http://$LocalIp:8530"
        kill -9 $MonPid 2>/dev/null
        kill -9 $ResPid  2>/dev/null
    fi
    if [ "$ResProt" = "rtmp" ]; then
       Target="rtmp://$LocalIp:1935/live"
        kill -9 $MonPid 2>/dev/null
        kill -9 $ResPid  2>/dev/null
    fi
    if [ "$ResProt" = "rtsp" ]; then
        Target="rtsp://$LocalIp:8554/live"
        kill -9 $MonPid 2>/dev/null
        kill -9 $ResPid  2>/dev/null
    fi
    }
#--------------------------------------------------------------------------

ResMon () {
    if [ "$Remonitor" = "0" ]; then
        return
    fi
    sleep $MonWait
      if [ "$MonPlayer" =  "ffplay" ]; then
    nohup ffplay -loglevel panic -nostats -window_title "$VideoLink-on-$Target" -volume 2 -vf  scale=340:260 $Target >/dev/null 2>&1 &
    MonPid="$!"
    disown
    return
     fi
 #    if [ "$MonPlayer" =  "vlc" ]; then
 #    nohup vlc --meta-title "$VideoLink-on-$Target"  --no-audio "$Target"  >/dev/null 2>&1 &
 #    MonPid="$!"
 #    disown
 #       return
 #   fi
    if [ "$MonPlayer" =  "mpv" ]; then
        nohup mpv --title="$VideoLink-on-$Target" --force-window=immediate --no-ytdl --autofit=240x160  --volume=10 $Target >/dev/null 2>&1 &
        MonPid="$!"
        disown
        return
    fi
    nohup $MonPlayer $Target >/dev/null 2>&1 &
    MonPid="$!"
    disown
}

#----------------------------------------------------------------------------------

VideoLink="$1"
 if [ ''$VideoLink'' != "" ]; then
    Restream
    exit
fi
while [ 1 ]; do
    clear
    printf "%s\n>>>>> ${BGreen}Drop/insert here a link to restream locally${NC} <<<<<\n\n" 
    read VideoLink
    if [ "$VideoLink" = '' ]; then
        continue
    fi
    Restream
done
exit
