#!/bin/bash

set -e
set -x

stream_server="rtmp://118.24.38.152:1935"
process_name="ffmpeg"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"

echo $SCRIPT_DIR

stop() {
    ps -ef|grep "${process_name}"|grep -v grep|awk '{print $2}'|xargs -I{} kill -9 {}
}


start() {
    gst_count=$(ps -ef | grep "${process_name}" | grep -v grep| wc -l)
    if [ $gst_count -ge 4 ]; then
        exit 0
    fi
    
    if [ $gst_count -gt 0 ]; then
        ps -ef|grep "${process_name}"|grep -v grep|awk '{print $2}'|xargs -I{} kill -9 {}
        sleep 3
    fi

    nohup ffmpeg -rtsp_transport tcp -i rtsp://admin:123456@192.168.10.81:554/chn1m -c copy -f flv rtmp://118.24.38.152:1935/qirui-live/$1/01 >/dev/null 2>&1 &
    nohup ffmpeg -rtsp_transport tcp -i rtsp://admin:123456@192.168.10.81:554/chn2m -c copy -f flv rtmp://118.24.38.152:1935/qirui-live/$1/02 >/dev/null 2>&1 &
    nohup ffmpeg -rtsp_transport tcp -i rtsp://admin:123456@192.168.10.81:554/chn3m -c copy -f flv rtmp://118.24.38.152:1935/qirui-live/$1/03 >/dev/null 2>&1 &
    nohup ffmpeg -rtsp_transport tcp -i rtsp://admin:123456@192.168.10.81:554/chn4m -c copy -f flv rtmp://118.24.38.152:1935/qirui-live/$1/04 >/dev/null 2>&1 &
}

if [ $# -eq 0 ]; then
    stop
    echo "Usage: $0 [veh01 | veh02 | veh03 | stop]"
    exit 1
else
    case $1 in
        veh01)
            start veh01
        ;;
        veh02)
            start veh02
        ;;
        veh03)
            start veh03
        ;;
        stop)
            stop
        ;;
        *)
            echo "Usage: $0 [veh01 | veh02 | veh03 | stop]"
            exit 1
        ;;
    esac
fi
