//           ___   ____               ___       ___
// \ \  / / | _   |  __| \ \  / / || | __  || || _ |
//  \ \/ /  |___  | |__   \ \/ /  || |___  || ||___|
//   \  /   | _   | _  |   \  /   ||  __ | || ||\\
//    \/    |___  |___ |    \/    || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir

package main

import (
	"flag"
	"log"
	"os"
	"runtime"
	"runtime/pprof"
	"vegvisir/pkg/server"
)

var (
	cFile = flag.String("c", "vegvisir.json", "Path to config file")

	// for profiling...
	cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")
	memprofile = flag.String("memprofile", "", "write memory profile to `file`")
)

func main() {

	flag.Parse()
	// cpu profiling
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal("could not create CPU profile: ", err)
		}
		defer f.Close() // error handling omitted for example
		if err := pprof.StartCPUProfile(f); err != nil {
			log.Fatal("could not start CPU profile: ", err)
		}
		defer pprof.StopCPUProfile()
	}

	server.NewServer(*cFile).Run()

	// memory profiling
	if *memprofile != "" {
		f, err := os.Create(*memprofile)
		if err != nil {
			log.Fatal("could not create memory profile: ", err)
		}
		defer f.Close() // error handling omitted for example
		runtime.GC()    // get up-to-date statistics
		if err := pprof.WriteHeapProfile(f); err != nil {
			log.Fatal("could not write memory profile: ", err)
		}
	}
}