package utils

import (
	"bufio"
	"fmt"
	"os"
	"syscall"

	"code.justin.tv/d8a/buddy/cmd/buddy-cli/setup"
	"code.justin.tv/twitch/cli/ghutil"
	"github.com/fatih/color"
	"github.com/spf13/cobra"
	"golang.org/x/crypto/ssh/terminal"
)

var authCmd = &cobra.Command{
	Use:   "auth",
	Short: "Retrieve an oauth2 token for your user, authorized to create and modify repositories",
	Long:  "When `buddy auth` is entered, the user will be prompted for username and password, then the credential pair will be used to authorize the RDS Buddy application to create repositories and check in code.",
	RunE: func(command *cobra.Command, args []string) error {
		fmt.Print("Github Enterprise User: ")
		scanner := bufio.NewScanner(os.Stdin)
		if !scanner.Scan() {
			return scanner.Err()
		}

		user := scanner.Text()

		fmt.Print("Github Enterprise Password: ")
		passwordBytes, err := terminal.ReadPassword(syscall.Stdin)
		fmt.Println()

		if err != nil {
			return err
		}

		password := string(passwordBytes)

		authRequest := &ghutil.GithubAuthorizationRequest{
			Scopes:       []string{"repo"},
			Note:         "buddy",
			NoteURL:      "https://git-aws.internal.justin.tv/d8a/buddy",
			ClientID:     "7a8f99269d2b313ff028",
			ClientSecret: "fcf53f7a743907d3382fb808cb2b90aaca438c03",
			Fingerprint:  "",
		}

		token, err := ghutil.GetCLIToken(user, password, "", authRequest)
		if err != nil {
			if !ghutil.IsOTP(err) {
				return err
			}

			fmt.Print("2FA One-Time Password: ")
			scanner := bufio.NewScanner(os.Stdin)
			if !scanner.Scan() {
				return scanner.Err()
			}

			otp := scanner.Text()

			token, err = ghutil.GetCLIToken(user, password, otp, authRequest)
			if err != nil {
				return err
			}
		}

		fmt.Println()
		fmt.Printf("You have %s retrieved the OAuth token for buddy!\n", color.GreenString("successfully"))
		fmt.Printf("Your token: %s\n", color.GreenString(token))
		fmt.Println()

		fmt.Printf("Add this token as a sandstorm secret to the secret %s\n", color.GreenString("<your team>/rds-buddy-store/<environment>/github_oauth"))
		fmt.Println("Then, you'll be ready to puppet your buddy server to configure your repos!")
		fmt.Println()

		return nil
	},
}

func init() {
	setup.RootCmd.AddCommand(authCmd)

	//RootCmd's PersistentPreRunE has a lot of stuff that stops authCmd from running
	//(like requiring buddy.cfg where authcmd doesn't require it).  Set PersistentPreRunE
	//to a non-nil dummy value to prevent RootCmd's from running.
	authCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
		return nil
	}
}
