#!/bin/sh -e
#
# tgo - go project - make a tmpdir and cd to it or create `~/.tmp/tgo`

tmp_go() {
  d="$(pwgen 10)"
  mkdir "/tmp/${d}"
  printf "%s\n" "/tmp/${d}"
  cd "/tmp/${d}"
  printf "package main\n\nfunc main() {\n\t\n}\n" >main.go
  "${EDITOR:-vi}" "+normal Gk" +startinsert! main.go && go run main.go
}

# create go project `~/.tmp/go`
tgo() {
  tgo_path="${HOME}/.tmp/tgo"
  mkdir -p "${tgo_path}"

  # check if the first argument is exists
  if [ -n "${1}" ]; then
    # shellcheck disable=SC2312
    tmp="$(mktemp -p "${tgo_path}" -d "${1}_$(date +%Y%m%d)_XXXXXX")"
    (
      cd "${tmp}"
      go mod init "$(basename "${tmp}")"
      cat >"main.go" <<-EOF
package main

func main() {
}
EOF
      cat >"main_test.go" <<-EOF
package main_test

import (
	"os"
	"testing"
)

func TestMain(m *testing.M) {
	os.Exit(m.Run())
}

func BenchmarkMain(b *testing.B) {
	b.ReportAllocs()
	for n := 0; n < b.N; n++ {

	}
}
EOF

      "${EDITOR:-vi}" -p main.go main_test.go
      echo "${tmp}"
    )
  else
    choice=$(find "${tgo_path}" -maxdepth 1 -type d -exec basename {} \; | fzf) \
      && (cd "${tgo_path}/${choice}" \
        && "${EDITOR:-vi}" -p main.go main_test.go)
  fi
}

if command -v go >/dev/null 2>&1; then
  case "$1" in
    h | home)
      tgo "$@"
      ;;
    -h | --help)
      printf '%s\n' "Usage: $(basename "$0") - make tmpdir & cd to it (default)
                 [h|home] - make ~/.tmp/go/'name' & fzf"
      exit 0
      ;;
    *)
      tmp_go
      ;;
  esac
else
  printf '%s\n' "Go is not installed. visit: <https://go.dev/dl/>"
  exit 1
fi

# tmp="$(mktemp -p /tmp -d "tgo_$(date +%Y%m%d)_XXXXXX")"

# printf "package main\n\nfunc main() {\n\n}\n" > "$tmp/main.go"
# printf "package main\n\nfunc TestMain(t *testing.T) {\n\n}\n\n" > "$tmp/main_test.go"
# printf "func BenchmarkMain(b *testing.B) {\n\tb.ReportAllocs()\n\tfor n := 0; n < b.N; n++ {\n\t}\n}\n" >> "$tmp/main_test.go"

# printf "module %s\n" "$(basename "$tmp")" > "$tmp/go.mod"

#   (
#       cd "$tmp"
#       ${EDITOR:-vi} -p main.go main_test.go
#       echo "$tmp"
#   )
