/*
Copyright 2021 The Kubernetes 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.
*/

package gce

import (
	"crypto/rand"
	"encoding/hex"
	"os"
	"strings"
	"time"

	"k8s.io/klog/v2"
	"sigs.k8s.io/kubetest2/pkg/exec"
)

func GCSBucketName(projectID, prefix string) string {
	var s string
	if jobID := os.Getenv("PROW_JOB_ID"); len(jobID) >= 4 {
		s = jobID[:4]
	} else {
		b := make([]byte, 2)
		rand.Read(b)
		s = hex.EncodeToString(b)
	}
	bucket := strings.Join([]string{projectID, prefix, s}, "-")
	return bucket
}

func EnsureGCSBucket(bucketPath, region, projectID string, public bool) error {
	lsArgs := []string{
		"gcloud", "storage", "ls", "--buckets",
	}
	if projectID != "" {
		lsArgs = append(lsArgs, "--project", projectID)
	}
	lsArgs = append(lsArgs, bucketPath)

	klog.Info(strings.Join(lsArgs, " "))
	cmd := exec.Command(lsArgs[0], lsArgs[1:]...)

	output, err := exec.CombinedOutputLines(cmd)
	if err == nil {
		return nil
	}
	notFound := false
	for _, line := range output {
		if strings.Contains(line, "not found: 404") {
			notFound = true
		}
	}
	if !notFound {
		klog.Info(output)
		return err
	}

	mbArgs := []string{
		"gcloud", "storage", "buckets", "create",
	}
	if projectID != "" {
		mbArgs = append(mbArgs, "--project", projectID)
	}
	if region != "" {
		mbArgs = append(mbArgs, "--location", region)
	}
	mbArgs = append(mbArgs, bucketPath)

	klog.Info(strings.Join(mbArgs, " "))
	cmd = exec.Command(mbArgs[0], mbArgs[1:]...)

	exec.InheritOutput(cmd)
	err = cmd.Run()
	if err != nil {
		return err
	}

	if public {
		iamArgs := []string{
			"gcloud", "storage", "buckets", "add-iam-policy-binding",
			"--member=allUsers", "--role=roles/storage.objectViewer",
		}
		iamArgs = append(iamArgs, bucketPath)
		klog.Info(strings.Join(iamArgs, " "))
		// GCS APIs are strongly consistent but this should help with flakes
		time.Sleep(10 * time.Second)
		cmd = exec.Command(iamArgs[0], iamArgs[1:]...)
		exec.InheritOutput(cmd)
		err = cmd.Run()
		if err != nil {
			return err
		}
	}
	return nil
}

func DeleteGCSBucket(bucketPath, projectID string) error {
	rmArgs := []string{
		"gcloud", "storage", "rm", "--recursive",
		"--billing-project", projectID,
		bucketPath,
	}

	klog.Info(strings.Join(rmArgs, " "))
	cmd := exec.Command(rmArgs[0], rmArgs[1:]...)

	exec.InheritOutput(cmd)
	err := cmd.Run()
	if err != nil {
		return err
	}
	return nil
}
