/**************************************************************************************
 *
 *     Project:    kvmstoreserver
 *     File name:  stage0.go
 *     Version:    1.0.0
 *     Date:       2018-01-14
 *
 *     Autor:      Bogdanovic Theodor
 *     Contact:    t.bogdanovic@hotmail.com
 *
 *     License:    GPLv3
 *
 **************************************************************************************/
/**************************************************************************************
 * Copyright 2018 Bogdanovic Theodor
 *
 * This file is part of kvmstoreserver.
 *
 * kvmstoreserver is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * kvmstoreserver 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with kvmstoreserver.  If not, see <http://www.gnu.org/licenses/>.
 **************************************************************************************/
/**************************************************************************************
 *  Further explanations:  This source code is under the license specified by the
 *                         Autor above. Core components or other packages are still
 *                         in source code form, under the license specified by the
 *                         respective author.
 **************************************************************************************/

package main

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"strings"
	"syscall"
	conf "utils/configMap"
	"utils/configPoller"

	log "github.com/judwhite/logrjack"
)

//*****************************************************************************
//*
//*      Structure: appServer
//*
//*****************************************************************************

// appServer is a unit-like structure. it is empty and serves
// only as a method wrapper for the http instance
type appServer struct{}

//******************** Methods ************************************************

// start starts the HTTP instance in stage0_ext3
func (slf *appServer) start() {

	log.Infof("Starting HTTP frontend - kvmstoreserver is online and listen on http://%v:%v",
		conf.GetStringOf("http_hostname"), conf.GetStringOf("http_port"))

	httpFrontend.start()
}

// wait activated when the HTTP server goes off. prevents the
// end before the graceful shutdown procedure is finished
func (slf *appServer) wait() { shutdown.wg.Wait() }

//*****************************************************************************
//*
//*      storeserver startup initiator
//*
//*****************************************************************************

// newAppServer creates a new wrapper instance and initialize
// all components in the following order:
//
// 1.) set configMap
// 2.) set configPoller
// 3.) set logrjack log engine
// 4.) init (load) Btree
// 5.) init Middleware Chains
// 6.) init a new HTTP instance
// 7.) init a separate goroutine for shutdown signals (only sigint and sigterm)
func newAppServer(testMode bool, overridePath string) *appServer {

	if testMode {
		conf.Settings(overridePath)
		log.Infof("Starting storeserver in test mode with a different config -> %v",
			overridePath)
	} else {
		conf.Settings(pathFromCmd())
	}

	// Register config reader in config poller
	configPoller.RegisterReaders(60, conf.GetConfigMapRef())

	log.Setup(log.Settings{
		Filename:    conf.GetStringOf("default_log_file"),
		MaxSizeMB:   (int)(conf.GetInt32Of("log_max_size_mb")),
		MaxAgeDays:  (int)(conf.GetInt32Of("log_max_age_days")),
		WriteStdout: conf.GetBoolOf("log_write_to_console"),
	})

	log.Info(
		"Start config poller in a seperate goroutine with a polling interval of -> 60 Seconds",
	)

	log.Info("******************** Initialze start procedure ********************")
	initializeBtree()

	log.Info("Initialize Middleware components and final handlers")
	initializeMiddleware()

	log.Info("Initialize a new HTTP server instance")
	initializeHTTPInstance()

	initializeShutdownWatcher()
	signal.Notify(shutdown.signalChan, syscall.SIGINT, syscall.SIGTERM)
	go shutdown.captureSignal()

	var as appServer

	return &as
}

//*****************************************************************************
//*
//*      Private Methods
//*
//*****************************************************************************

// Parse command line args if the param -config is set
func pathFromCmd() string {

	pathToConfig := flag.String("config", "",
		"The path to the main configuration file")
	flag.Parse()

	trimmedConfigPath := strings.Trim(*pathToConfig, " ")
	if trimmedConfigPath == "" {
		fmt.Println("Missing path to config file -> -config=<Path to valid config file>")
		os.Exit(-1)
	}

	return *pathToConfig
}
