// This file is part of gnunet-gns-registrar, a GNS registrar service.
// Copyright (C) 2022 Martin Schanzenbach
//
// gnunet-gns-registrar 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.
//
// gnunet-gns-registrar 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/>.
//
// SPDX-License-Identifier: AGPL3.0-or-later

package main

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

	"github.com/schanzen/taler-go/pkg/merchant"
	gnsregistrar "gnunet.org/gnunet-gns-registrar/pkg/rest"
	"gopkg.in/ini.v1"
	"rsc.io/getopt"
)

var (
	t        gnsregistrar.Registrar
	version  string
	datahome string
	verbose  bool // FIXME do something with this?
)

func handleRequests(r *gnsregistrar.Registrar) {
	log.Fatal(http.ListenAndServe(r.Cfg.Ini.Section("gns-registrar").Key("bind_to").MustString("localhost:11000"), r.Router))
}

func printHelp() {
	fmt.Print("gnunet-gns-registrar\n\n")
	getopt.PrintDefaults()
	fmt.Print("\nReport bugs to gnunet-developers@gnu.org.\n",
		"Home page: https://taler.net\n",
		"General help using GNU software: http://www.gnu.org/gethelp/\n")
}

func main() {
	var cfgFlag = flag.String("c", "", "Configuration file to use")
	getopt.Alias("c", "config")
	// FIXME use flags
	loglevelStringOpt := flag.String("L", "INFO", "Log level to use. DEBUG, INFO, WARNING or ERROR")
	getopt.Alias("L", "loglevel")
	var verboseFlag = flag.Bool("v", false, "Verbose")
	getopt.Alias("v", "verbose")
	var helpFlag = flag.Bool("h", false, "Print help")
	getopt.Alias("h", "help")

	getopt.Parse()
	cfgfile := "gns-registrar.conf"
	log.Println(version)
	if len(*cfgFlag) != 0 {
		cfgfile = *cfgFlag
	}
	if *helpFlag {
		printHelp()
		return
	}
	verbose = *verboseFlag
	loglevel := gnsregistrar.LogInfo
	for loglevelNum, loglevelString := range gnsregistrar.LoglevelStringMap {
		if loglevelString == *loglevelStringOpt {
			loglevel = loglevelNum
		}
	}
	cfg, err := ini.LooseLoad(cfgfile)
	if err != nil {
		log.Fatalf("Failed to read config: %v", err)
		os.Exit(1)
	}
	merchURL := cfg.Section("gns-registrar").Key("base_url_merchant").MustString("https://backend.demo.taler.net")
	merchToken := cfg.Section("gns-registrar").Key("merchant_token").MustString("sandbox")
	t := gnsregistrar.Registrar{}
	t.Initialize(gnsregistrar.RegistrarConfig{
		Ini:      cfg,
		Version:  version,
		Datahome: datahome,
		Loglevel: loglevel,
		Merchant: merchant.NewMerchant(merchURL, merchToken),
	})
	handleRequests(&t)
}
