package main

import (
	"errors"
	"fmt"
	"log"
	"net/url"
	"os"
	"strings"

	"github.com/urfave/cli/v2"
)

func insertToken(token, cloneUrl string) (string, error) {
	parsedUrl, err := url.Parse(cloneUrl)
	if err != nil {
		return "", err
	}

	// Ensure we're given an HTTP(s) URL
	if parsedUrl.Scheme != "http" && parsedUrl.Scheme != "https" {
		return "", errors.New("URL scheme is not http(s)")
	}

	parsedUrl.User = url.User(token)
	return parsedUrl.String(), nil
}

func run(ctx *cli.Context) error {
	envName := ctx.String("token-env")
	cloneUrl := ctx.String("clone-url")

	tokenSecret := ""
	for _, env := range os.Environ() {
		parts := strings.Split(env, "=")
		if parts[0] == envName {
			tokenSecret = parts[1]
			break
		}
	}
	if tokenSecret == "" {
		os.Exit(1)
	}

	res, err := insertToken(tokenSecret, cloneUrl)
	if err != nil {
		return err
	}

	fmt.Printf("%s\n", res)
	return nil
}

func main() {
	app := &cli.App{
		Name: "ci-wrapper",
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:     "clone-url",
				Required: true,
				Usage:    "URL the repository has been cloned from",
			},
			&cli.StringFlag{
				Name:     "token-env",
				Required: true,
				Usage:    "Environment variable the secret is in",
			},
		},
		Action: run,
	}
	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}
