#!/usr/bin/env bash

# Execute by: bash xxx.sh or bash zzz/yyy/xxx.sh or ./xxx.sh or ./zzz/yyy/xxx.sh source xxx.sh
REALPATH=$(realpath ${BASH_SOURCE[0]})
SCRIPT_DIR=$(cd $(dirname ${REALPATH}) && pwd)
WORK_DIR=$(cd $(dirname ${REALPATH}) && pwd)
echo "BASH_SOURCE=${BASH_SOURCE}, REALPATH=${REALPATH}, SCRIPT_DIR=${SCRIPT_DIR}, WORK_DIR=${WORK_DIR}"
cd ${WORK_DIR}

DATA_HOME=/data
WELL_KNOWN=${DATA_HOME}/.well-known
IMAGE=ossrs/oryx:5
MGMT_PORT=2022
HTTPS_PORT=2443
RTMP_PORT=1935
RTC_PORT=8000
SRT_PORT=10080
NGINX_RELOAD="/etc/init.d/nginx reload"

echo -n "DATA_HOME=${DATA_HOME}, WELL_KNOWN=${WELL_KNOWN}, IMAGE=${IMAGE}, MGMT_PORT=${MGMT_PORT}, RTMP_PORT=${RTMP_PORT}"
echo -n ", RTC_PORT=${RTC_PORT}, SRT_PORT=${SRT_PORT}, NGINX_RELOAD=${NGINX_RELOAD}"
echo ", HTTPS_PORT=${HTTPS_PORT}, EXTRA_PARAMS=${EXTRA_PARAMS}"

echo "Force to stop platform container"
docker rm -f oryx 2>/dev/null

echo "Start platform container"
CMD="docker run -v ${DATA_HOME}:/data -v ${WELL_KNOWN}:/data/.well-known ${EXTRA_PARAMS}
    -p ${MGMT_PORT}:2022/tcp -p ${HTTPS_PORT}:2443/tcp -p ${RTMP_PORT}:1935/tcp
    -p ${RTC_PORT}:8000/udp -p ${SRT_PORT}:10080/udp
    --log-driver=json-file --log-opt=max-size=1g --log-opt=max-file=3
    --restart no -it --name oryx --detach
    ${IMAGE}"
echo $CMD && $CMD
if [[ $? -ne 0 ]]; then echo "Start platform container failed"; exit 1; fi
echo "Start platform container ok"

# Show all logs of container.
docker logs -f oryx &

function handle_signals() {
    echo "Signal $1 received. Cleaning up and exiting..."

    ID=$(docker ps --filter "name=oryx" --format "{{.ID}}")
    if [[ ! -z $ID ]]; then
        docker stop oryx
        docker rm -f oryx 2>/dev/null
    fi

    exit 0
}

trap 'handle_signals SIGTERM' SIGTERM
trap 'handle_signals SIGINT' SIGINT

function do_reload() {
    files=$(ls $DATA_HOME/signals/nginx.reload.* 2>/dev/null)
    for file in $files; do
        echo "Got ${#files[@]} reload signals" && rm -f $files
        if [[ -f /etc/init.d/nginx ]]; then
            $NGINX_RELOAD && echo "Reload nginx ok"
            if [[ $? -ne 0 ]]; then echo "Reload nginx failed"; exit 1; fi
        fi
        break
    done
}

while true; do
    ID=$(docker ps --filter "name=oryx" --format "{{.ID}}")
    if [[ -z $ID ]]; then
        echo "Platform container not found"
        docker stop oryx 2>/dev/null
        docker rm -f oryx 2>/dev/null
        exit 1
    fi

    docker ps -a --filter "name=oryx" --format "{{.Names}} {{.ID}} {{.Ports}}"
    for (( i=0; i<3; i++ )); do
        do_reload
        sleep 1
    done
done
