// AskForConfirmation returns true if the user types one of the "okayResponses"
// See also: ConfirmChoice()
// https://gist.github.com/albrow/5882501
320539
func AskForConfirmation() bool {

	// Hopefully a clean exit
	interrupt := make(chan os.Signal, 1)
	stop := make(chan os.Signal, 1)
	reload := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)
	signal.Notify(stop, syscall.SIGINT)
	signal.Notify(reload, syscall.SIGHUP)
	go func() {
		select {
		case signal := <-interrupt:
			fmt.Println("Got signal:", signal)
			fmt.Println("Dying")
			os.Exit(0)
		case signal := <-reload:
			fmt.Println("Got signal:", signal)
			fmt.Println("Dying")
			os.Exit(0)
		case signal := <-stop:
			fmt.Printf("Got signal:%v\n", signal)
			fmt.Println("Dying")
			os.Exit(0)
		}
	}()

	var response string

	_, err := fmt.Scanln(&response)
	if err != nil {
		//fmt.Println(err)
		return false
	}
	okayResponses := []string{"y", "Y", "yes", "Yes", "YES"}
	nokayResponses := []string{"n", "N", "no", "No", "NO", "\n"}
	quitResponses := []string{"q", "Q", "exit", "quit"}
	if containsString(okayResponses, response) {
		return true
	} else if containsString(nokayResponses, response) {
		return false
	} else if containsString(quitResponses, response) {
		return false
	} else {
		fmt.Println("\nNot valid answer, try again. [y/n] [yes/no]")
		return AskForConfirmation()
	}
}
1132381
func (release *nextRelease) PromptUserToConfirmStart() (bool, error) {
	// Fetch the stories already assigned to the release.
	var (
		ver       = release.trunkVersion
		verString = ver.BaseString()
	)
	task := fmt.Sprintf("Fetch GitHub issues already assigned to release %v", verString)
	log.Run(task)
	assignedIssues, err := release.tracker.issuesByRelease(ver)
	if err != nil {
		return false, errs.NewError(task, err)
	}

	// Collect the issues that modified trunk since the last release.
	task = "Collect the issues that modified trunk since the last release"
	log.Run(task)
	issueNumsString, err := releases.ListStoryIdsToBeAssigned(release.tracker)
	if err != nil {
		return false, errs.NewError(task, err)
	}

	// Turn []string into []int.
	issueNums := make([]int, len(issueNumsString))
	for i, numString := range issueNumsString {
		// numString is #ISSUE_NUMBER.
		num, err := strconv.Atoi(numString[1:])
		if err != nil {
			panic(err)
		}
		issueNums[i] = num
	}

	// Drop the stories that are already assigned.
	numSet := make(map[int]struct{}, len(assignedIssues))
	for _, issue := range assignedIssues {
		numSet[*issue.Number] = struct{}{}
	}
	nums := make([]int, 0, len(issueNums))
	for _, num := range issueNums {
		if _, ok := numSet[num]; !ok {
			nums = append(nums, num)
		}
	}
	issueNums = nums

	// Fetch the collected issues from GitHub, if necessary.
	var additionalIssues []*github.Issue
	if len(issueNums) != 0 {
		task = "Fetch the collected issues from GitHub"
		log.Run(task)

		var err error
		additionalIssues, err = release.tracker.issuesByNumber(issueNums)
		if err != nil {
			return false, errs.NewError(task, err)
		}

		// Drop stories already assigned to another release.
		notAssigned := make([]*github.Issue, 0, len(additionalIssues))
		for _, issue := range additionalIssues {
			switch {
			case issue.Milestone == nil:
				notAssigned = append(notAssigned, issue)
			default:
				log.Warn(fmt.Sprintf(
					"Skipping issue #%v: modified trunk, but already assigned to milestone '%v'",
					*issue.Number, *issue.Milestone.Title))
			}
		}
		additionalIssues = notAssigned
	}

	// Print the summary into the console.
	summary := []struct {
		header string
		issues []*github.Issue
	}{
		{
			"The following issues were manually assigned to the release:",
			assignedIssues,
		},
		{
			"The following issues were added automatically (modified trunk):",
			additionalIssues,
		},
	}
	for _, item := range summary {
		if len(item.issues) != 0 {
			fmt.Println()
			fmt.Println(item.header)
			fmt.Println()
			err := storyprompt.ListStories(
				toCommonStories(item.issues, release.tracker), os.Stdout)
			if err != nil {
				return false, err
			}
		}
	}

	// Ask the user to confirm.
	ok, err := prompt.Confirm(
		fmt.Sprintf("\nAre you sure you want to start release %v?", verString), false)
	if err == nil {
		release.additionalIssues = additionalIssues
	}
	return ok, err
}
445246
func ConfirmPassword(previous string) Func {
	return func(input string) error {
		err := Password(input)
		if err != nil {
			return err
		}

		if input != previous {
			return NewValidationError("The password you provided does not match the previous password you provided!")
		}

		return nil
	}
}
357722
func AskForStaticValueOptional(s string) string {
	reader := bufio.NewReader(os.Stdin)

	return getStaticValue(reader, s)
}
1007114
func (s *GetIntentOutput) SetConfirmationPrompt(v *Prompt) *GetIntentOutput {
	s.ConfirmationPrompt = v
	return s
}
1201609
func RespondWithHelpConfused(in *dt.Msg) string {
	if in.Plugin != nil {
		use := randUseForPlugin(in.Plugin)
		use2 := randUseForPlugin(in.Plugin)
		if use == use2 {
			return fmt.Sprintf("%s You can try telling me %q",
				ConfusedLang(), use)
		}
		return fmt.Sprintf("%s You can try telling me %q or %q",
			ConfusedLang(), use, use2)
	}
	if len(PluginsGo) == 0 {
		return ConfusedLang()
	}
	use := randUse()
	use2 := randUse()
	if use == use2 {
		return fmt.Sprintf("%s How about %q", ConfusedLang(), use)
	}
	return fmt.Sprintf("%s How about %q or %q", ConfusedLang(), use, use2)
}
584439
func askToTrustHost(addr, algo, fingerprint string) bool {
	var ans string

	fmt.Fprintf(os.Stderr, promptToTrustHost, addr, algo, fingerprint)
	fmt.Scanf("%s\n", &ans)

	ans = strings.ToLower(ans)
	if ans != "yes" && ans != "y" {
		return false
	}

	return true
}
338694
func complexValueConfirmation(target string) (bool, error) {
	if forceConvertComplexValue {
		return true, nil
	}

	var response string
	fmt.Printf("Found complex value %s. Convert? (y or n) ", target)
	_, err := fmt.Scanln(&response)
	if err != nil {
		return false, err
	}

	if len(response) == 0 {
		return false, err
	}

	if response[0] == 'y' || response[0] == 'Y' {
		return true, nil
	} else if response[0] == 'n' || response[0] == 'N' {
		return false, nil
	} else {
		fmt.Println("Unexpected response")
		return complexValueConfirmation(target)
	}
}
933000
func (service *Service) CheckRegistrationSMSConfirmation(w http.ResponseWriter, r *http.Request) {
	registrationSession, err := service.GetSession(r, SessionForRegistration, "registrationdetails")
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	response := map[string]bool{}

	if registrationSession.IsNew {
		// TODO: registrationSession is new with SMS, something must be wrong
		log.Info("Registration session timed out while polling for phone confirmation")
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}
	sessionKey, _ := registrationSession.Values["sessionkey"].(string)
	if sessionKey == "" {
		log.Debug("Polling for sms confirmation without session key")
		sessions.Save(r, w)
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}

	registeringUser, err := registration.NewManager(r).GetRegisteringUserBySessionKey(sessionKey)
	if err != nil {
		log.Error("Failed to load registering user object: ", err)
		sessions.Save(r, w)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	confirmed, err := service.phonenumberValidationService.IsConfirmed(r, registeringUser.PhoneValidationKey)
	if err == validation.ErrInvalidOrExpiredKey {
		confirmed = true //This way the form will be submitted, let the form handler deal with redirect to login
		return
	}
	if err != nil {
		log.Error("Failed to check if phone is confirmed in registration flow: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	response["confirmed"] = confirmed

	if confirmed {
		persistentlog.NewManager(r).SaveLog(persistentlog.New(sessionKey, persistentlog.RegistrationFlow, "Users phone is confirmed"))
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}
923369
func CreateConfirmModal(title string, x, y, width, height int, fg, bg termbox.Attribute) *ConfirmModal {
	i := ConfirmModal{title: title, x: x, y: y, width: width, height: height, fg: fg, bg: bg, activeFg: fg, activeBg: bg}
	if i.title == "" && i.text == "" {
		i.title = "Confirm?"
	}
	i.showHelp = true
	return &i
}
483981
func (r *CheckCertificateRPC) CheckCertificate(c context.Context, req *admin.CheckCertificateRequest) (*admin.CheckCertificateResponse, error) {
	// Deserialize the cert.
	der, err := utils.ParsePEM(req.CertPem, "CERTIFICATE")
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "can't parse 'cert_pem' - %s", err)
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "can't parse 'cert-pem' - %s", err)
	}

	// Find a checker for the CA that signed the cert, check the certificate.
	checker, err := GetCertChecker(c, cert.Issuer.CommonName)
	if err == nil {
		_, err = checker.CheckCertificate(c, cert)
		if err == nil {
			return &admin.CheckCertificateResponse{
				IsValid: true,
			}, nil
		}
	}

	// Recognize error codes related to CA cert checking. Everything else is
	// transient errors.
	if details, ok := err.(Error); ok {
		return &admin.CheckCertificateResponse{
			IsValid:       false,
			InvalidReason: details.Error(),
		}, nil
	}
	return nil, status.Errorf(codes.Internal, "failed to check the certificate - %s", err)
}
1312851
func (s *PutIntentOutput) SetConfirmationPrompt(v *Prompt) *PutIntentOutput {
	s.ConfirmationPrompt = v
	return s
}
182391
func (service *Service) Check2FASMSConfirmation(w http.ResponseWriter, request *http.Request) {

	sessionInfo, err := service.getLoginSessionInformation(request, "")
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	response := map[string]bool{}
	if sessionInfo == nil {
		response["confirmed"] = false
	} else {
		response["confirmed"] = sessionInfo.Confirmed
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)

}
1205979
func (service *IYOPhonenumberValidationService) IsConfirmed(request *http.Request, key string) (confirmed bool, err error) {
	info, err := service.getPhonenumberValidationInformation(request, key)
	if err != nil {
		return
	}
	if info == nil {
		err = ErrInvalidOrExpiredKey
		return
	}
	confirmed = info.Confirmed
	return
}
1309914
func MultipleConfirm(times int, isTenable func() bool, retryInterval time.Duration) bool {
	for i := 0; i < times; i++ {
		if !isTenable() {
			return false
		}
		time.Sleep(retryInterval)
	}

	return true
}
120782
func PromptConfirmed(entity string, fn func(string) error) string {
	for {
		value, err := PromptLine(fmt.Sprintf("Choose %s", entity))
		if err != nil {
			logger.Error(err)
		}
		err = fn(value)
		if err == nil {
			return value
		}
		logger.Printf("Error: %v", err)
	}
}
884339
func AskForKeyImport(ctx context.Context, key string, names []string) bool {
	if ctxutil.IsAlwaysYes(ctx) {
		return true
	}
	if !ctxutil.IsInteractive(ctx) {
		return false
	}

	ok, err := AskForBool(ctx, fmt.Sprintf("Do you want to import the public key '%s' (Names: %+v) into your keyring?", key, names), false)
	if err != nil {
		return false
	}

	return ok
}