#!/bin/bash

# path to script (base of repo)
BASE_DIR="$( dirname "${BASH_SOURCE[0]}" )"

# Some workaround for Win MINGW64 and CYGWIN
case $( uname -a ) in
    *"MINGW64"*)
        NGINX_DIR="$BASE_DIR/external_nginx"
        WINDOWS=1
        MINGW=1
        ;;
    *"CYGWIN"*)
        NGINX_DIR="$BASE_DIR/external_nginx"
        WINDOWS=1
        CYGWIN=1
        ;;
    *)
        NGINX_DIR="$( cd "$BASE_DIR" >/dev/null 2>&1 && pwd )/external_nginx"
        ;;
esac

function common_win_actions {
    mkdir -p "$BASE_DIR/logs" "$BASE_DIR/temp"
    tasklist -fo csv -nh -fi "imagename eq nginx.exe" | grep -q nginx.exe
    if [ $? -eq '0' ] ; then
        RED="\033[1;31m"
        NC="\033[0m" # No Color
        printf "${RED}WARN!${NC} other Nginx process is already started, old configs may be applied"
    fi
}

function stop_nginx {
    nginx -s stop -c "$NGINX_DIR/nginx.conf" -g "pid $NGINX_DIR/nginx.pid;"
}

function pure_start {
    $1 nginx -c "$NGINX_DIR/nginx.conf" -g "pid $NGINX_DIR/nginx.pid;"
}

function start_nginx {
    if [ $WINDOWS ] ; then
        common_win_actions
    fi

    if [ $MINGW ] ; then
        pure_start 'start //b'
    elif [ $CYGWIN ] ; then
        cygstart --hide bash "$BASE_DIR/ext_nginx" pure_start
    else
        pure_start
    fi
}

function restart_nginx {
    stop_nginx
    sleep 1
    start_nginx
}

case "$1" in
    start)
        start_nginx
        ;;
    pure_start)
        pure_start
        ;;
    stop)
        stop_nginx
        ;;
    restart)
        restart_nginx
        ;;
    *)
        exit 1
        ;;
esac

exit 0
