package main

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

func main() {
	wd, err := os.Getwd()
	if err != nil {
		fmt.Print("$ ")
		return
	}
	cwd, err := filepath.EvalSymlinks(wd)
	if err != nil {
		fmt.Print("$ ")
		return
	}
	emoji := resolveEmoji()

	var promptRoot string
	gitRoot := gitRoot()
	if gitRoot == os.Getenv("HOME") {
		promptRoot = "~"
	} else {
		promptRoot = filepath.Base(gitRoot)
	}
	// subtract the git toplevel "/home/j3s"
	// from the cwd "/home/j3s/code/nongitdir"
	// to get the suffix "/code/nongitdir"
	// os.cwd gets the symlink, git does not
	suffix := cwd[len(gitRoot):]
	fmt.Printf("%s %s", emoji, promptRoot)

	var parts []string
	parts = strings.Split(suffix, "/")
	for i, part := range parts {
		if i == len(parts)-1 {
			fmt.Printf("%s", part)
		} else {
			if len(part) != 0 {
				fmt.Printf("%c/", part[0])
			} else {
				fmt.Printf("/")
			}
		}
	}
}

func resolveEmoji() string {
	hostname, _ := os.Hostname()
	if hostname == "zora" {
		return "🌸"
	}
	if hostname == "rose" {
		return "🌹"
	}
	return "💀"
}

// getRepoRoot returns the full path to the root
// of the closest git dir
func gitRoot() string {
	path, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
	if err != nil {
		// assume the error means there's no git
		// dir above us, or git isn't installed.
		return "/"
	}
	return strings.TrimSpace(string(path))
}
