package main

import (
	"fmt"
	"os"
	"strings"

	"gitlab.com/cinnamon/voiceagent/icsconf"
	"gitlab.com/cinnamon/voiceagent/icserror"
	"gitlab.com/cinnamon/voiceagent/icslog"
	"gitlab.com/cinnamon/voiceagent/icsutil"
)

func main() {
	if icsutil.CheckPID() {
		fmt.Println("Voice Agent Already Running. Terminating...")
		os.Exit(0)
	} else {
		//get Voice Agent home dir
		isStop := false
		var homeDir string
		for _, e := range os.Environ() {
			s := strings.SplitN(e, "=", 2)
			if strings.Compare(s[0], "ICSVA_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/icsva.xml", homeDir)
		//configFile := fmt.Sprintf("%s/config/icsvc.xml", service.GetHomeDir())
		//fmt.Println("Config file:", configFile)
		conf, confErr := icsconf.OpenConfig(configFile, homeDir)
		if confErr != nil {
			confErr.PrintWithCaller(0)
			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 Voice Agent Loader")

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

		// icsLog.Printf(icslog.LOG_LEVEL_INFO, -1, "Loaded Voice Agent[%d]", pid)

		//deamonize
		pid, derr := icsutil.DeamonizeProcessCheck()
		if derr != nil {
			icserror.ICSERRDeamonize.SetError(derr)
			icsLog.Printf(icslog.LOG_LEVEL_ERROR, -1, "voiceagent process check: %s", icserror.ICSERRDeamonize.GetError())
			os.Exit(0)
		}
		icsLog.Printf(icslog.LOG_LEVEL_INFO, -1, "Loaded Voice Agent[%d]", pid)
	}
}
