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

import (
	"crypto/sha512"
	"flag"
	"fmt"
	"log"
	"net/url"
	"os"

	"gopkg.in/ini.v1"
	"taler.net/taldir/internal/util"
)

// Generates a link from a challenge and address
func generateLink(host string, addr string, challenge string) string {
	h := sha512.New()
	h.Write([]byte(addr))
	h_addr := util.Base32CrockfordEncode(h.Sum(nil))
	return host + "/register/" + url.QueryEscape(h_addr) + "/" + url.QueryEscape(challenge) + "?address=" + url.QueryEscape(addr)
}

func main() {
	var solveFlag = flag.Bool("s", false, "Provide a solution for the challenge/pubkey")
	var linkFlag = flag.Bool("l", false, "Provide a link for activation")
	var challengeFlag = flag.String("c", "", "Activation challenge")
	var pubkeyFlag = flag.String("p", "", "Public key")
	var addressFlag = flag.String("a", "", "Address")
	flag.Parse()
	cfgfile := "taldir.conf"
	_cfg, err := ini.LooseLoad(cfgfile)
	if err != nil {
		log.Fatalf("Failed to read config: %v", err)
		os.Exit(1)
	}
	host := _cfg.Section("taldir").Key("base_url").MustString("http://localhost")
	if *solveFlag {
		if len(*challengeFlag) == 0 || len(*pubkeyFlag) == 0 {
			fmt.Println("You need to provide an activation challenge and a public key to generate a solution")
			os.Exit(1)
		}
		fmt.Println(util.GenerateSolution(*pubkeyFlag, *challengeFlag))
		os.Exit(0)
	}
	if *linkFlag {
		if len(*challengeFlag) == 0 || len(*addressFlag) == 0 {
			fmt.Println("You need to provide an activation challenge and an address to generate a link")
			os.Exit(1)
		}
		fmt.Println(generateLink(host, *addressFlag, *challengeFlag))
		os.Exit(0)
	}
}
