package new

import (
	"fmt"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"strings"
)

/* try to get git user, if not system user */
func getName() string {
	out, err := exec.Command("git", "config", "user.name").Output()
	if err == nil {
		s := strings.TrimSpace(string(out))
		if s != "" {
			return s
		}
	}
	u, err := user.Current()
	if err == nil && u.Username != "" {
		return u.Username
	}
	return "unknown"
}

/* helper function for writing files */
func write(path string, format string, args ...interface{}) error {
	dir := filepath.Dir(path)
	if err := os.MkdirAll(dir, 0755); err != nil {
		panic(err)
	}
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	_, err = fmt.Fprintf(f, format, args...)
	return err
}

/* creates a hello world project */
func Project(dir string) error {
	if err := os.Mkdir(dir, 0755); err != nil {
		return err
	}
	if err := os.Chdir(dir); err != nil {
		return err
	}
	write("www/index.lua", `local fes = require("fes")
local site = fes.fes()

site:h1("Hello, World!")

return site`)
	write("Fes.toml", `[app]

name = "%s"
version = "0.0.1"
authors = ["%s"]`, dir, getName())
	return nil
}
