package request

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

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

const geminiHomeDocBase = "/home/gemini/users"

func ProcessGemini(requestRootPath string) error {
	rp := filepath.Join(requestRootPath, "gemini")

	files, err := ioutil.ReadDir(rp)
	if err != nil {
		return fmt.Errorf("failed to list directory %s: %w", rp, err)
	}

	usernames := []string{}

	for _, file := range files {
		usernames = append(usernames, file.Name())
	}

	if len(usernames) == 0 {
		return nil
	}

	for _, username := range usernames {
		err := linkGemini(username)
		if err != nil {
			fmt.Fprintf(os.Stderr, "failed to process gemini request for %s: %s\n", username, err.Error())
		}

		os.Remove(filepath.Join(rp, username))
	}

	return nil
}

func linkGemini(username string) error {
	pgPath := filepath.Join("/home", username, "public_gemini")
	if !pathExists(pgPath) {
		return fmt.Errorf("public_gemini missing for %s", username)
	}

	geminiPath := filepath.Join(geminiHomeDocBase, username)

	if !pathExists(geminiPath) {
		err := os.Symlink(pgPath, geminiPath)
		if err != nil {
			return fmt.Errorf("failed to link public_gemini for %s: %w", username, err)
		}
	}
	body := fmt.Sprintf(`hi %s!

you requested a gemini space on the town. this space has been activated and anything you do in your public_gemini directory should now be reflected by the server.

if you did _not_ request this, please let an admin know.`, username)
	return email.SendLocalEmail(username, "gemini", body)
}

func pathExists(path string) bool {
	_, err := os.Stat(path)
	return err == nil
}
