package main

// #cgo LDFLAGS:  -L/usr/local/lib /usr/local/lib/libavcodec.a /usr/local/lib/libavformat.a /usr/local/lib/llibavutil.a /usr/local/lib/llibswscale.a -llibswresample.a -llibavdevice -llibavfilter

import (
	"fmt"
	"os"
	"strings"

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

func main() {
	service := icssvc.NewService()

	///////////////////////////////////
	//Demonize service
	//check Voice Gateway pid file - ICSVS_ROOT/voicegateway.pid
	//if already running, terminate self.
	/*
		if icsutil.CheckPID() {
			service.ShowServiceInfo()
			fmt.Println("Voice Gateway Already Running. Terminating...")
			os.Exit(0)
		}
	*/

	/*
		//deamonize
		pid, derr := icsutil.Deamonize()
		if derr != nil {
			service.ShowServiceInfo()
			icserror.ICSERRDeamonize.SetError(derr)
			fmt.Println("voice Gateway:", icserror.ICSERRDeamonize)
			os.Exit(0)
			return
		}
		fmt.Println("PID", pid)
	*/ ////////////////////////

	//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)
		return
	}
	if confErr := service.SetIcsConfig(conf); confErr != nil {
		confErr.PrintWithCaller(0)
	}

	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)
	}

	service.SetIcsLog(icsLog)
	//create log watcher
	go service.LogWatcher()

	info := service.ShowServiceInfo()
	info += fmt.Sprintf("iComsys Voice Statistics Home: %s\n", homeDir)
	fmt.Printf("iComsys Voice Statistics Home: %s\n", homeDir)
	//wd, err := os.Getwd()
	logpath := conf.LogConfig.Path
	info += fmt.Sprintf("Available Disk Space [%s]: %d MB\n", logpath, icsutil.GetDiskAvailableSpace(logpath)/1024/1024)
	fmt.Printf("Available Disk Space [%s]: %d MB\n", logpath, icsutil.GetDiskAvailableSpace(logpath)/1024/1024)
	info += conf.ShowConfig()

	//check license expiration
	//fmt.Println("Remain Expiration Months:", conf.GetRemainExpire())

	app := icsapp.Init(conf)
	//fmt.Printf("Service Started - %d\n================================\n", pid)

	info = "\n" + info
	icsLog.Print(icslog.LOG_LEVEL_INFO, -1, info)
	icsLog.Print(icslog.LOG_LEVEL_INFO, -1, "Service Started")
	icsLog.Print(icslog.LOG_LEVEL_INFO, -1, "================================")

	/////////////////////////////////
	//icsutil.CloseSTDIO()
	/////////////////////////////////

	execerr := app.Execute()
	if execerr != nil {
		execerr.PrintWithCaller(1)
		os.Exit(1)
	}

	/*
		deviceName := conf.GetDeviceName()
		pcap := icspcap.New()
		//pcap.SetFilter("")
		packetSource, pcapErr := pcap.Init(deviceName)
		//packetSource, icserr := pcap.Init("wlp1s0")
		if pcapErr != nil {
			if pcapErr.Equal(icserror.ICSERRPCAPOpenLive) {
				fmt.Printf("Device Name: %s\n", deviceName)
			}
			pcapErr.Print()
			return
		}
		fmt.Println("Filter:", pcap.GetFilter())

		if err := pcap.Run(packetSource); err != nil {
			err.Print()
		}
		defer pcap.Close()
	*/

}
