package main

import (
	"errors"
	"fmt"
	"os"
	"strings"

	"git.tilde.town/tildetown/town/email"
)

const emailText = `hello!

You (hopefully) requested to add a new public key to your tilde.town account.

If you didn't, feel free to ignore this email (or report it to an admin).

If you did, here is your auth code: %s

To use this code, please open a terminal and run:

ssh help@tilde.town

Follow the instructions there to add your new key and restore access to your account.

best,
~vilmibm`

func loadPassword() (string, error) {
	f, err := os.Open("/town/docs/smtp_help.pw")
	if err != nil {
		return "", fmt.Errorf("could not open smtp password file: %w", err)
	}

	pw := make([]byte, 100)

	n, err := f.Read(pw)
	if err != nil {
		return "", fmt.Errorf("could not read smtp password file: %w", err)
	}
	if n == 0 {
		return "", errors.New("smtp password file was empty")
	}

	return strings.TrimSpace(string(pw[0:n])), nil
}

func sendAuthCodeEmail(ac AuthCode) error {
	pw, err := loadPassword()
	if err != nil {
		return err
	}

	body := fmt.Sprintf(emailText, ac.Code)

	mailer := email.NewExternalMailer(pw)
	return mailer.Send(
		ac.Email,
		"Adding a new tilde.town public key",
		body)
}
