// This file is part of taldir, the Taler Directory implementation.
// Copyright (C) 2022 Martin Schanzenbach
//
// Taldir 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.
//
// Taldir 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

/* TODO
- ToS API (terms, privacy) with localizations
- Prettify QR code landing page
- Base32: Use gnunet-go module? (currently copied)
- OrderId processing
- Maintenance of database: When to delete expired validations?
*/

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

	"database/sql"

	_ "github.com/lib/pq"
	"github.com/schanzen/taler-go/pkg/merchant"
	"github.com/schanzen/taler-go/pkg/util"
	"rsc.io/getopt"
	taldir "taler.net/taldir/pkg/taldir"
)

var (
	version        string
	taldirdatahome string
	taldirconfdir  string
)

func handleRequests(t *taldir.Taldir) {
	log.Fatal(http.ListenAndServe(t.Cfg.Ini.GetString("directory", "bind_to", "localhost:11000"), t.Router))
}

func printHelp() {
	fmt.Print("taler-directory\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 helpFlag = flag.Bool("h", false, "Print help")
	getopt.Alias("h", "help")
	var versionFlag = flag.Bool("v", false, "Print version")
	getopt.Alias("v", "version")

	getopt.Parse()
	cfgfile := path.Join(taldirconfdir, "taldir.conf")
	if len(*cfgFlag) != 0 {
		cfgfile = *cfgFlag
	}
	if *helpFlag {
		printHelp()
		return
	}
	if *versionFlag {
		fullName, err := os.Executable()
		if err != nil {
			log.Panic(err)
		}
		fmt.Printf("%s %s", filepath.Base(fullName), version)
		return
	}
	loglevel := taldir.LogInfo
	for loglevelNum, loglevelString := range taldir.LoglevelStringMap {
		if loglevelString == *loglevelStringOpt {
			loglevel = loglevelNum
		}
	}
	t := taldir.Taldir{}
	cfg, err := util.LoadConfiguration(cfgfile)
	if err != nil {
		log.Fatalf("Failed to read config: %v", err)
		os.Exit(1)
	}
	psqlconn := cfg.GetString("directory-pq", "connection_string", "postgres:///taler-directory")

	db, err := sql.Open("postgres", psqlconn)
	if err != nil {
		log.Panic(err)
	}
	defer db.Close()
	merchURL := cfg.GetString("directory", "merchant_base_url", "https://backend.demo.taler.net")
	merchToken := cfg.GetString("directory", "merchant_token", "sandbox")
	t.Initialize(taldir.TaldirConfig{
		Ini:      cfg,
		Version:  version,
		Datahome: taldirdatahome,
		Db:       db,
		Loglevel: loglevel,
		Merchant: merchant.NewMerchant(merchURL, merchToken),
	})
	handleRequests(&t)
}
