/*
Copyright 2015 The Kubernetes Authors All rights reserved.

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 pulls

// A simple binary for merging PR that match a criteria
// Usage:
//   submit-queue -token=<github-access-token> -user-whitelist=<file> --jenkins-host=http://some.host [-min-pr-number=<number>] [-dry-run] [-once]

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	github_util "k8s.io/contrib/mungegithub/github"
	"k8s.io/kubernetes/pkg/util/sets"

	"github.com/golang/glog"
	"github.com/spf13/cobra"
)

var (
	_ = fmt.Print
)

// RefreshWhitelist updates the whitelist, re-getting the list of committers.
func (sq *SubmitQueue) RefreshWhitelist(config *github_util.Config) {
	info := map[string]userInfo{}
	if sq.additionalUserWhitelist == nil {
		users, err := loadWhitelist(sq.Whitelist)
		if err != nil {
			glog.Fatalf("error loading user whitelist: %v", err)
		}
		sq.additionalUserWhitelist = &users
	}

	if sq.committerList == nil {
		committerList, err := loadWhitelist(sq.Committers)
		if err != nil {
			glog.Fatalf("error loading committers whitelist: %v", err)
		}
		sq.committerList = &committerList
	}

	// We must use the values on disk in case it has users which don't have
	// explicit "pull" permission in the API
	allUsers := sets.NewString(sq.additionalUserWhitelist.List()...)

	pushUsers, pullUsers, err := config.UsersWithAccess()
	if err != nil {
		glog.Info("Falling back to static committers list.")
		allUsers = allUsers.Union(*sq.committerList)
		sq.userWhitelist = &allUsers
		return
	}
	for _, user := range pullUsers {
		allUsers.Insert(*user.Login)
		info[*user.Login] = userInfo{
			Access:    "pull access",
			AvatarURL: *user.AvatarURL,
		}
	}
	for _, user := range pushUsers {
		allUsers.Insert(*user.Login)
		info[*user.Login] = userInfo{
			Access:    "push access",
			AvatarURL: *user.AvatarURL,
		}
	}

	// Anyone we got from a config file and not from the API we need to look up info
	for _, login := range allUsers.List() {
		if _, ok := info[login]; ok {
			continue
		}
		user, err := config.GetUser(login)
		if err != nil {
			glog.Errorf("Unable to get user information about %q", login)
			continue
		}
		info[login] = userInfo{
			Access:    "explicitly whitelisted",
			AvatarURL: *user.AvatarURL,
		}
	}
	sq.userWhitelist = &allUsers
	sq.userInfo = info
	return
}

func loadWhitelist(file string) (sets.String, error) {
	result := sets.String{}
	if len(file) == 0 {
		return result, nil
	}
	fp, err := os.Open(file)
	if err != nil {
		return result, err
	}
	defer fp.Close()
	scanner := bufio.NewScanner(fp)
	for scanner.Scan() {
		current := scanner.Text()
		if !strings.HasPrefix(current, "#") {
			result.Insert(current)
		}
	}
	return result, scanner.Err()
}

func writeWhitelist(fileName, header string, users sets.String) error {
	items := append([]string{header}, users.List()...)
	items = append(items, "")
	return ioutil.WriteFile(fileName, []byte(strings.Join(items, "\n")), 0640)
}

func (sq *SubmitQueue) doGenCommitters(config *github_util.Config) error {
	pushUsers, pullUsers, err := config.UsersWithAccess()
	if err != nil {
		glog.Fatalf("Unable to read committers from github: %v", err)
	}

	pushSet := sets.NewString()
	for _, user := range pushUsers {
		pushSet.Insert(*user.Login)
	}
	pullSet := sets.NewString()
	for _, user := range pullUsers {
		pullSet.Insert(*user.Login)
	}

	if err = writeWhitelist(sq.Committers, "# auto-generated by "+os.Args[0]+" gen-committers; manual additions should go in the whitelist", pushSet); err != nil {
		glog.Fatalf("Unable to write committers: %v", err)
	}
	glog.Info("Successfully updated committers file.")

	existingWhitelist, err := loadWhitelist(sq.Whitelist)
	if err != nil {
		glog.Fatalf("error loading whitelist; it will not be updated: %v", err)
	}

	neededInWhitelist := existingWhitelist.Difference(pushSet)
	neededInWhitelist = neededInWhitelist.Union(pullSet)
	if err = writeWhitelist(sq.Whitelist, "# auto-generated by "+os.Args[0]+" gen-committers; manual additions may be added by hand", neededInWhitelist); err != nil {
		glog.Fatalf("Unable to write additional user whitelist: %v", err)
	}
	glog.Info("Successfully update whitelist file.")
	return nil
}

func (sq *SubmitQueue) addWhitelistCommand(root *cobra.Command, config *github_util.Config) {
	genCommitters := &cobra.Command{
		Use:   "gencommiters",
		Short: "Generate the list of people with commit access",
		RunE: func(_ *cobra.Command, _ []string) error {
			if err := config.PreExecute(); err != nil {
				return err
			}
			return sq.doGenCommitters(config)
		},
	}
	root.PersistentFlags().StringVar(&sq.Whitelist, "user-whitelist", "./whitelist.txt", "Path to a whitelist file that contains users to auto-merge.  Required.")
	root.PersistentFlags().StringVar(&sq.Committers, "committers", "./committers.txt", "File in which the list of authorized committers is stored; only used if this list cannot be gotten at run time.  (Merged with whitelist; separate so that it can be auto-generated)")
	root.Flags().StringVar(&sq.WhitelistOverride, "whitelist-override-label", "ok-to-merge", "Github label, if present on a PR it will be merged even if the author isn't in the whitelist")

	root.AddCommand(genCommitters)
}
