#!/bin/bash

#==============全局变量定义 start=======================
#运行模块名
MODULE_NAME="audit"
#定义环境变量
export GOPATH=/opt/gowww/audit

MAIN_FILE="$GOPATH/src/app/main.go"
RUNTIME="$GOPATH/runtime"
BUILT_FILE="$GOPATH/src/app/${MODULE_NAME}"
LOG_FILE="$RUNTIME/run.log"
#保存pid的临时文件,可按情况进行修改，比如放到/run/passport.pid
PID_FILE="$RUNTIME/${MODULE_NAME}.pid"
RUN_COMMAMD=${BUILT_FILE}" > "${LOG_FILE}" 2>&1"

#==============全局变量定义 end=========================

#==============修改运行环境 start===================

init(){
	#运行环境
	runmode=$RUNMODE
	#http端口
	httpport=$HTTPPORT
	
	if [ "$runmode"x = ""x ]; then
	    runmode="prod"
	fi
	echo "runmode="$runmode
	sed -i "s/^runmode.*/runmode=$runmode/g"  $GOPATH/src/app/conf/app.conf
	
	if [ "$httpport"x != ""x ]; then
		echo "httpport="$httpport
	    sed -i "s/^httpport.*/httpport=$httpport/g"  $GOPATH/src/app/conf/app.conf
	fi
}

#==============修改运行环境 end======================
start(){
	echo "start $MODULE_NAME"

	if [ ! -e $BUILT_FILE ]; then
		echo "no built file: ${BUILT_FILE}. start fail"
		return 1
	fi

	if [ ! -e $LOG_FILE ]; then
		touch $LOG_FILE
	fi
	
	#检查PID文件是否存在
	if [ -e $PID_FILE ]
	then
		#检查PID是否正在运行
		pid=`cat $PID_FILE`
		res=`ps aux|awk -v pid=$pid '{if($2 == pid) {print $2}}'`
		if [ "$pid" = "$res" ] ;then
			echo "has pid file: $PID_FILE,pid=$pid, $MODULE_NAME already run."
			return 0
	    fi
	fi
	#echo $RUN_COMMAMD
    eval $RUN_COMMAMD

    if [ $? -ne 0 ] ;then            
        return 1
    fi
}

#创建运行目录 
create_runtime(){
	if [ ! -e $RUNTIME ]; then
		mkdir -p $RUNTIME
	fi
}


#==========================================
#执行命令
#==========================================
create_runtime
init

#keep running
echo "DEBUG="$DEBUG
if [ "$DEBUG"x = "1"x ]; then
    exec "/bin/bash"
else
	start
fi
