package main

import (
	"bytes"
	"crypto/rsa"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"strings"
	"time"

	"github.com/contiamo/go-base/v3/pkg/tokens"
	jwt "github.com/dgrijalva/jwt-go"
	flag "github.com/spf13/pflag"
)

func main() {
	// var publicKeyPath string
	var privateKeypath string
	var opts tokens.Options

	// flag.StringVar(&publicKeyPath, "public-key-path", "../../config/auth/idp.crt", "path to file containing the public key for JWT token verification")
	flag.StringVar(&privateKeypath, "private-key-path", "../../config/auth/idp.key", "path to file containing the private key for signing a JWT token")
	flag.StringVar(&opts.ProjectID, "project-id", "e473c1cc-598c-4a75-9a60-84f5dec53f9b", "project id value to set in the token claims")
	flag.StringVar(&opts.Audience, "audience", "", "audience value to set in the token claims")

	flag.Parse()
	key, err := GetPrivateKey(privateKeypath)
	if err != nil {
		log.Fatal(err)
	}
	creator := tokens.NewCreator("localdev", key, 60*time.Minute)

	token, err := creator.Create("test-token", opts)
	if err != nil {
		log.Fatal(err)
	}

	parts := strings.Split(token, ".")
	b, err := jwt.DecodeSegment(parts[1])
	if err != nil {
		log.Fatal(err)
	}

	var out bytes.Buffer
	json.Indent(&out, b, "", "  ")
	fmt.Print("Claims:\n")
	fmt.Println(out.String())

	fmt.Printf("export token=%s\n", token)

	fmt.Printf("\nToken:\n%s\n", token)
}

// GetPublicKey gets the encryption key from a given path
func GetPublicKey(path string) (publicKey *rsa.PublicKey, err error) {
	if path == "" {
		log.Fatalf("path to the public key file is empty")
	}

	keyBytes, err := ioutil.ReadFile(path)
	if err != nil {
		log.Fatalf("can not read the public key file `%s`: %s", path, err)
	}

	return jwt.ParseRSAPublicKeyFromPEM(keyBytes)
}

// GetPrivateKey gets the encryption key from a given path
func GetPrivateKey(path string) (privateKey *rsa.PrivateKey, err error) {
	if path == "" {
		log.Fatalf("path to the private key file is empty")
	}

	keyBytes, err := ioutil.ReadFile(path)
	if err != nil {
		log.Fatalf("can not read the private key file `%s`: %s", path, err)
	}

	return jwt.ParseRSAPrivateKeyFromPEM(keyBytes)
}
