// 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"

	"gopkg.in/ini.v1"
	"gorm.io/driver/postgres"
	taldir "taler.net/taldir/pkg/rest"
)

var (
	t              taldir.Taldir
	version        string
	taldirdatahome string
)

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

func main() {
	var cfgFlag = flag.String("c", "", "Configuration file to use")

	flag.Parse()
	log.Println(version)
	cfgfile := "taldir.conf"
	if len(*cfgFlag) != 0 {
		cfgfile = *cfgFlag
	}
	t := taldir.Taldir{}
	cfg, err := ini.LooseLoad(cfgfile)
	if err != nil {
		log.Fatalf("Failed to read config: %v", err)
		os.Exit(1)
	}
	psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		cfg.Section("taldir-pq").Key("host").MustString("localhost"),
		cfg.Section("taldir-pq").Key("port").MustInt64(5432),
		cfg.Section("taldir-pq").Key("user").MustString("taldir"),
		cfg.Section("taldir-pq").Key("password").MustString("secret"),
		cfg.Section("taldir-pq").Key("db_name").MustString("taldir"))
	db := postgres.Open(psqlconn)
	cfg.WriteTo(os.Stdout)
	t.Initialize(taldir.TaldirConfig{
		Ini:      cfg,
		Version:  version,
		Datahome: taldirdatahome,
		Db:       db,
	})
	handleRequests(&t)
}
