#!/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}

echo "Start SRS server, WORK_DIR:${WORK_DIR}"

# Load the environment variables for SRS server.
if [[ -f ${WORK_DIR}/containers/data/config/.srs.env ]]; then
    echo "Load variables for SRS from ${WORK_DIR}/containers/data/config/.srs.env"
    echo "export $(grep -v '^#' ${WORK_DIR}/containers/data/config/.srs.env | xargs)"
    export $(grep -v '^#' ${WORK_DIR}/containers/data/config/.srs.env | xargs)
fi

# Get the metadata of machine.
if [[ -f ${WORK_DIR}/containers/data/config/.env ]]; then source ${WORK_DIR}/containers/data/config/.env; fi
echo "LoadEnv CLOUD=$CLOUD REGION=$REGION, SOURCE=$SOURCE"

SRS_PARAMS="-c ${WORK_DIR}/containers/conf/srs.release.conf"
echo "Run srs-server $SRS_PARAMS"

# Make sure the config file exists.
mkdir -p ${WORK_DIR}/containers/data/config &&
touch ${WORK_DIR}/containers/data/config/srs.server.conf ${WORK_DIR}/containers/data/config/srs.vhost.conf
if [[ $? -ne 0 ]]; then echo "Make sure the config file exists failed"; exit 1; fi

# TODO: FIXME: Remove it after SRS supports empty config file.
# See https://github.com/ossrs/srs/pull/3768
if [[ ! -s ${WORK_DIR}/containers/data/config/srs.server.conf ]]; then
    echo '# OK' > ${WORK_DIR}/containers/data/config/srs.server.conf
fi
if [[ ! -s ${WORK_DIR}/containers/data/config/srs.vhost.conf ]]; then
    echo '# OK' > ${WORK_DIR}/containers/data/config/srs.vhost.conf
fi

# Current directory should be /usr/local/oryx/platform
# We don't check the exit value, see https://github.com/ossrs/srs/issues/3757
/usr/local/srs/objs/srs $SRS_PARAMS
if [[ $? -ne 0 ]]; then echo "Warning: SRS start with none zero, but might be ok, see #3757."; fi

SRS_PID_FILE="./objs/srs.pid"

for ((i=0; i<10; i++)); do
if [[ -f $SRS_PID_FILE ]]; then
  ps -p `cat $SRS_PID_FILE` 1>/dev/null 2>/dev/null &&
  echo "SRS server started, pid=`cat $SRS_PID_FILE`" &&
  break
fi
sleep 0.3
done

ps -p `cat $SRS_PID_FILE` 1>/dev/null 2>/dev/null
if [[ $? -ne 0 ]]; then echo "Check SRS failed"; exit 1; fi
