package main

import (
	"fmt"
	"os"
	"strings"

	"gitlab.com/ics_cinnamon/voiceStatistics/icsconf"
	"gitlab.com/ics_cinnamon/voiceStatistics/icserror"
	"gitlab.com/ics_cinnamon/voiceStatistics/icslog"
	"gitlab.com/ics_cinnamon/voiceStatistics/icsutil"
)

func main() {
	if icsutil.CheckPID() {
		fmt.Println("VoiceGateway Already Running. Terminating...")
		os.Exit(0)
	}

	//get Voice Gateway home dir
	isStop := false
	var homeDir string
	for _, e := range os.Environ() {
		s := strings.SplitN(e, "=", 2)
		if strings.Compare(s[0], "ICSVS_ROOT") == 0 {
			homeDir = s[1]
			//service.SetHomeDir(s[1])
			isStop = true
			break
		}
	}
	if !isStop {
		icserror.ICSERRNotFoundHome.PrintWithCaller(1)
		return
	}

	//configuration
	configFile := fmt.Sprintf("%s/config/icsvs.xml", homeDir)
	conf, confErr := icsconf.OpenConfig(configFile, homeDir)
	if confErr != nil {
		confErr.PrintWithCaller(0)
		fmt.Println(confErr.GetError())
		return
	}

	icsLog, lerr := icslog.NewIcsLog(
		&conf.LogConfig,
		icslog.GetLogLevelID(conf.LogConfig.Level),
		icslog.GetLogOutputID(conf.LogConfig.Output),
		conf.LogConfig.Path,
		conf.LogConfig.Disklimit,
	)
	if lerr != nil {
		lerr.PrintWithCaller(0)
	}

	icsLog.Print(icslog.LOG_LEVEL_INFO, -1, "Started VoiceGateway Loader")

	//deamonize
	pid, derr := icsutil.DeamonizeProcessCheck()
	if derr != nil {
		icserror.ICSERRDeamonize.SetError(derr)
		icsLog.Printf(icslog.LOG_LEVEL_ERROR, -1, "VoiceGateway : %s", icserror.ICSERRDeamonize.GetError())
		os.Exit(0)
	}

	icsLog.Printf(icslog.LOG_LEVEL_INFO, -1, "Loaded VoiceGateway[%d]", pid)
}
