#!/usr/bin/env bash

# omarchy:summary=Set up git identity, a default SSH key and skm, the SSH key manager
# omarchy:requires-sudo=true

# Based: skm has no package on either OS, so Go builds it into ~/.local/bin.
# A ~/.gitconfig with Neovim as the merge and diff tool is written when none
# exists. The identity and the key are asked for interactively, so from a
# non-interactive run only the tool installs.

set -eo pipefail

echo "Installing skm..."
omarchy-pkg-add git golang-go brew=go gum

mkdir -p ~/.local/bin
if omarchy-cmd-missing skm && [[ ! -x ~/.local/bin/skm ]]; then
  echo "Building skm..."
  GOBIN="$HOME/.local/bin" go install github.com/TimothyYe/skm/cmd/skm@latest
fi
export PATH="$HOME/.local/bin:$PATH"

if [[ ! -e ~/.gitconfig ]]; then
  cat >~/.gitconfig <<'GITCONFIG'
[init]
	defaultBranch = main
[pull]
	rebase = false
[merge]
	tool = nvim
	conflictstyle = merge
[mergetool]
	keepTemporaries = false
	keepBackup = false
[mergetool "nvim"]
	cmd = nvim -d $LOCAL $REMOTE $MERGED -c '$wincmd w' -c 'wincmd J'
[diff]
	tool = nvim
[difftool "nvim"]
	cmd = nvim -d $LOCAL $REMOTE
[filter "lfs"]
	process = git-lfs filter-process
	required = true
	clean = git-lfs clean -- %f
	smudge = git-lfs smudge -- %f
GITCONFIG
fi

if [[ ! -t 0 ]]; then
  echo "Run this from a terminal to set the git identity and create the default SSH key."
  exit 0
fi

git_name=$(git config --global user.name 2>/dev/null || true)
git_email=$(git config --global user.email 2>/dev/null || true)
if [[ -z $git_name ]]; then
  git_name=$(gum input --placeholder "Full name for git commits" --header "")
  git config --global user.name "$git_name"
fi
if [[ -z $git_email ]]; then
  git_email=$(gum input --placeholder "Email for git commits" --header "")
  git config --global user.email "$git_email"
fi

mkdir -p ~/.ssh ~/.skm/default
chmod 700 ~/.ssh
if [[ ! -f ~/.ssh/id_rsa ]]; then
  if [[ ! -f ~/.skm/default/id_rsa ]]; then
    passphrase=$(gum input --password --placeholder "Passphrase for the new SSH key (empty for none)" --header "")
    ssh-keygen -t rsa -b 4096 -C "$git_email" -f ~/.skm/default/id_rsa -N "$passphrase" -q
  fi
  skm use default
elif [[ ! -f ~/.skm/default/id_rsa ]]; then
  cp ~/.ssh/id_rsa ~/.ssh/id_rsa.pub ~/.skm/default/
fi
chmod 600 ~/.skm/default/id_rsa ~/.ssh/id_rsa
chmod 644 ~/.skm/default/id_rsa.pub ~/.ssh/id_rsa.pub
