#!/bin/bash

script_dir=$(dirname "$(readlink -f "$0")")
grafana_dir=$(dirname "$script_dir")
user='grafana'
log_dir="logs/grafana.log"

ps -ef | grep -w "${grafana_dir}/bin/grafana" | grep -v 'grep' &>/dev/null
if [ $? -eq 0 ];then
  echo "error: !!!grafana server runing!!!"
  exit 10
fi

if [ "`whoami`" != "${user}" ];then
  echo "error: !!!Excute user not ${user}!!!"
  exit 10
fi

if [ ! -f "${grafana_dir}/bin/grafana" ];then
  echo "error: !!!grafana binary file not exist!!!"
  exit 10
fi

cd ${grafana_dir}

start_para=`cat ${grafana_dir}/script/running_paraments`

if [ -n "${start_para}" ];then
  nohup ${grafana_dir}/bin/grafana server \
  ${start_para} >> ${log_dir} 2>&1 &
else
  nohup ${grafana_dir}/bin/grafana >> ${log_dir} 2>&1 &
fi

sleep 2

ps -ef | grep -w "${grafana_dir}/bin/grafana" | grep -v 'grep' &>/dev/null
if [ $? -eq 0 ];then
  echo "success: grafana server start"
else
  echo "error: grafana server start failed"
  exit 10
fi
