package main

import (
	"flag"
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gitlab.iwarma.ru/iwa/dev/license/license_lib/api"
	"gitlab.iwarma.ru/iwa/dev/license/license_lib/config"
)

const (
	VERSION = "1.7.0"
)

var (
	configFile  = flag.String("config", "config.json", "Path to config file")
	versionFlag = flag.Bool("version", false, "Show version and exit")
)

func main() {
	cl := log.WithFields(log.Fields{"part": "main", "ver": VERSION})

	flag.Parse()

	if *versionFlag {
		cl.Infof("License client version %v", VERSION)
		return
	}

	//##############################
	//    Read and parse config
	//##############################

	// Viper config
	err := config.ReadCfg(*configFile)
	if err != nil {
		cl.Fatalf("%v", err)
	}

	//##############################
	//       Init logging
	//##############################
	err = initLogging()
	if err != nil {
		cl.Fatalf("%v", err)
	}

	cl.Infof("Starting")
	defer cl.Infof("Stopping")

	//##############################
	//           Api
	//##############################
	cl.Infof("Starting API on port %v", viper.GetInt(config.ApiPort))
	router := mux.NewRouter()
	router.HandleFunc("/token/", api.GetActivationToken).Methods("GET")
	router.HandleFunc("/activate/", api.ActivateLicense).Methods("POST")
	router.HandleFunc("/license/", api.GetLicenseInfo).Methods("GET")
	router.HandleFunc("/auto/", api.AutoLicenseActivation).Methods("GET")
	router.Use(api.LogUrlMiddleware)

	cl.Infof("API server starting on port %v", viper.GetInt(config.ApiPort))
	err = http.ListenAndServe(fmt.Sprintf(":%v", viper.GetInt(config.ApiPort)), router)
	if err != nil {
		cl.Fatalf("Can't start api: %v", err)
	}
}
