//
// Copyright 2022 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build e2e

package util

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"math/rand"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"golang.org/x/crypto/openpgp"
)

var (
	cli    = "rekor-cli"
	server = "rekor-server"
	keys   openpgp.EntityList
)

type GetOut struct {
	Attestation     string
	AttestationType string
	Body            interface{}
	LogIndex        int
	IntegratedTime  int64
}

// This was generated with gpg --gen-key, and all defaults.
// The email is "test@rekor.dev", and the name is Rekor Test.
// It should only be used for test purposes.

var secretKey = `-----BEGIN PGP PRIVATE KEY BLOCK-----

[encoded data, 4940 characters]
T4CBiqLxHYsQ9n8dT95t+poqJ10PVFkehb+8kh05e3ENd4xpkkdTfIY=
=CwjQ
-----END PGP PRIVATE KEY BLOCK-----`
var PrivateKey = `-----BEGIN PGP PRIVATE KEY BLOCK-----

[encoded data, 4940 characters]
T4CBiqLxHYsQ9n8dT95t+poqJ10PVFkehb+8kh05e3ENd4xpkkdTfIY=
=CwjQ
-----END PGP PRIVATE KEY BLOCK-----`

var PubKey = `-----BEGIN PGP PUBLIC KEY BLOCK-----

mQGNBF/11g0BDADciiDQKYjWjIZYTFC55kzaf3H7VcjKb7AdBSyHsN8OIZvLkbgx
1M5x+JPVXCiBEJMjp7YCVJeTQYixic4Ep+YeC8zIdP8ZcvLD9bgFumws+TBJMY7w
2cy3oPv/uVW4TRFv42PwKjO/sXpRg1gJx3EX2FJV+aYAPd8Z6pHxuOk6J49wLY1E
3hl1ZrPGUGsF4l7tVHniZG8IzTCgJGC6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IC KEY BLOCK-----`

func init() {
	p := os.Getenv("REKORTMPDIR")
	if p != "" {
		cli = path.Join(p, cli)
		server = path.Join(p, server)
	}
	var err error
	keys, err = openpgp.ReadArmoredKeyRing(strings.NewReader(secretKey))
	if err != nil {
		panic(err)
	}
}

func OutputContains(t *testing.T, output, sub string) {
	t.Helper()
	if !strings.Contains(output, sub) {
		t.Errorf("Expected [%s] in response, got %s", sub, output)
	}
}

func Run(t *testing.T, stdin, cmd string, arg ...string) string {
	t.Helper()
	arg = append([]string{coverageFlag()}, arg...)
	c := exec.Command(cmd, arg...)
	if stdin != "" {
		c.Stdin = strings.NewReader(stdin)
	}
	if os.Getenv("REKORTMPDIR") != "" {
		// ensure that we use a clean state.json file for each Run
		c.Env = append(c.Env, "HOME="+os.Getenv("REKORTMPDIR"))
	}
	b, err := c.CombinedOutput()
	if err != nil {
		t.Log(string(b))
		t.Fatal(err)
	}
	return stripCoverageOutput(string(b))
}

func RunCli(t *testing.T, arg ...string) string {
	t.Helper()
	arg = append(arg, rekorServerFlag())
	// use a blank config file to ensure no collision
	if os.Getenv("REKORTMPDIR") != "" {
		arg = append(arg, "--config="+os.Getenv("REKORTMPDIR")+".rekor.yaml")
	}
	return Run(t, "", cli, arg...)
}

func RunCliErr(t *testing.T, arg ...string) string {
	t.Helper()
	arg = append([]string{coverageFlag()}, arg...)
	arg = append(arg, rekorServerFlag())
	// use a blank config file to ensure no collision
	if os.Getenv("REKORTMPDIR") != "" {
		arg = append(arg, "--config="+os.Getenv("REKORTMPDIR")+".rekor.yaml")
	}
	cmd := exec.Command(cli, arg...)
	b, err := cmd.CombinedOutput()
	if err == nil {
		t.Log(string(b))
		t.Fatalf("expected error, got %s", string(b))
	}
	return stripCoverageOutput(string(b))
}

func rekorServerFlag() string {
	return fmt.Sprintf("--rekor_server=%s", rekorServer())
}

func rekorServer() string {
	if s := os.Getenv("REKOR_SERVER"); s != "" {
		return s
	}
	return "http://localhost:3000"
}

func coverageFlag() string {
	return "-test.coverprofile=/tmp/pkg-rekor-cli." + RandomSuffix(8) + ".cov"
}

func stripCoverageOutput(out string) string {
	return strings.Split(strings.Split(out, "PASS")[0], "FAIL")[0]
}

// RandomSuffix returns a random string of the given length.
func RandomSuffix(n int) string {
	const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

	b := make([]byte, n)
	for i := range b {
		b[i] = letterBytes[rand.Intn(len(letterBytes))]
	}
	return string(b)
}

// RandomData returns a random byte slice of the given size.
func RandomData(t *testing.T, n int) []byte {
	t.Helper()
	rand.Seed(time.Now().UnixNano())
	data := make([]byte, n)
	if _, err := rand.Read(data[:]); err != nil {
		t.Fatal(err)
	}
	return data
}

func CreateArtifact(t *testing.T, artifactPath string) string {
	t.Helper()
	// First let's generate some random data so we don't have to worry about dupes.
	data := RandomData(t, 100)

	artifact := base64.StdEncoding.EncodeToString(data[:])
	// Write this to a file
	write(t, artifact, artifactPath)
	return artifact
}

func write(t *testing.T, data string, path string) {
	t.Helper()
	if err := ioutil.WriteFile(path, []byte(data), 0644); err != nil {
		t.Fatal(err)
	}
}

func GetUUIDFromUploadOutput(t *testing.T, out string) string {
	t.Helper()
	// Output looks like "Artifact timestamped at ...\m Wrote response \n Created entry at index X, available at $URL/UUID", so grab the UUID:
	urlTokens := strings.Split(strings.TrimSpace(out), " ")
	url := urlTokens[len(urlTokens)-1]
	splitUrl := strings.Split(url, "/")
	return splitUrl[len(splitUrl)-1]
}
func SignPGP(b []byte) ([]byte, error) {
	var buf bytes.Buffer
	if err := openpgp.DetachSign(&buf, keys[0], bytes.NewReader(b), nil); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
func Write(t *testing.T, data string, path string) {
	t.Helper()
	if err := ioutil.WriteFile(path, []byte(data), 0644); err != nil {
		t.Fatal(err)
	}
}

// CreatedPGPSignedArtifact gets the test dir setup correctly with some random artifacts and keys.
func CreatedPGPSignedArtifact(t *testing.T, artifactPath, sigPath string) {
	t.Helper()
	artifact := CreateArtifact(t, artifactPath)

	// Sign it with our key and write that to a file
	signature, err := SignPGP([]byte(artifact))
	if err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(sigPath, signature, 0644); err != nil {
		t.Fatal(err)
	}
}

func GetUUIDFromTimestampOutput(t *testing.T, out string) string {
	t.Helper()
	// Output looks like "Created entry at index X, available at $URL/UUID", so grab the UUID:
	urlTokens := strings.Split(strings.TrimSpace(out), "\n")
	return GetUUIDFromUploadOutput(t, urlTokens[len(urlTokens)-1])
}

// SetupTestData is a helper function to setups the test data
func SetupTestData(t *testing.T) {
	// create a temp directory
	artifactPath := filepath.Join(t.TempDir(), "artifact")
	// create a temp file
	sigPath := filepath.Join(t.TempDir(), "signature.asc")
	CreatedPGPSignedArtifact(t, artifactPath, sigPath)

	// Write the public key to a file
	pubPath := filepath.Join(t.TempDir(), "pubKey.asc")
	if err := ioutil.WriteFile(pubPath, []byte(PubKey), 0644); err != nil { //nolint:gosec
		t.Fatal(err)
	}

	// Now upload to rekor!
	out := RunCli(t, "upload", "--artifact", artifactPath, "--signature", sigPath, "--public-key", pubPath)
	OutputContains(t, out, "Created entry at")
}
