/*
Copyright (c) 2018 Vereign AG [https://www.vereign.com]

This is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package main

import (
	"flag"

	"code.vereign.com/code/viam-apis/log"

	"code.vereign.com/code/key-storage-agent/config"
	"code.vereign.com/code/key-storage-agent/server"
)

// main start a gRPC server and waits for connection
func main() {
	//log.SetFlags(log.LstdFlags | log.Lshortfile)

	configFile := flag.String("config-file", "", "path to configuration file")
	etcdURL := flag.String("etcd-url", "", "etcd URL")
	flag.Parse()

	if *configFile == "" && *etcdURL == "" {
		log.Fatal("Config file path or etcd URL not specified")
		return
	}

	log.Printf("Loading configuration values...")
	err := config.LoadConfigValues(*configFile, *etcdURL)
	if err != nil {
		log.Fatalf("Exiting due to wrong configuration: %s", err)
	}

	grpcAddress := config.Config.GrpcListenAddress
	restAddress := config.Config.ListenAddress
	dataStorageAddress := config.Config.DataStorageAgentURL
	certPem := config.Config.Certification.CertificatePEM
	keyPem := config.Config.Certification.PrivateKeyPEM
	caCertPem := config.Config.Certification.CaCertificatePEM
	vereignCaCertificatePem := config.Config.Certification.VereignCertificatePEM

	maxMessageSize := config.Config.MaxMessageSize
	log.SetConfiguration(config.Config.GlobalLogLevel)

	// fire the gRPC server in a goroutine
	go func() {
		err := server.StartGRPCServer(grpcAddress, certPem, keyPem, caCertPem, vereignCaCertificatePem,
			dataStorageAddress, maxMessageSize)
		if err != nil {
			log.Fatalf("failed to start gRPC server: %s", err)
		}
	}()

	// fire the REST server in a goroutine
	go func() {
		err := server.StartRESTServer(restAddress, grpcAddress, certPem)
		if err != nil {
			log.Fatalf("failed to start gRPC server: %s", err)
		}
	}()

	go func() {
		err := server.StartPrometheusServer()
		if err != nil {
			log.Printf("failed to start prometheus server: %v", err)
		}
	}()

	// infinite loop
	log.Printf("Entering infinite loop")
	select {}
}