#!/bin/bash
# restore-dots files is idempotent
set -euf -o pipefail
# is-installed?
installed() {
  command -v "$1" >/dev/null 2>&1
}
fail() {
  echo "🔴 $@"
  exit 1
}
# which package manager
mgrinstall=""
if installed brew; then
  mgrinstall="brew -vd install"
elif installed apt-get; then
  # determine if we need to apt update
  curr=$(date +%s)
  last=$(stat -c %Y /var/lib/apt/lists/)
  diff=$(((curr - last) / 3600))
  if [ $diff -gt 24 ]; then
    echo "===> apt update..."
    apt-get update
  fi
  export DEBIAN_FRONTEND=noninteractive
  mgrinstall="apt-get -y install"
elif installed yum; then
  mgrinstall="yum -y install"
else
  # TODO if darwin, prompt to install brew
  fail "no package manager (brew/apt) found"
fi
# install dependencies
$mgrinstall curl git fish jq
# securely fetch the keys from GitHub
mkdir -p ~/.ssh/
KEYS=$(curl -s https://api.github.com/meta | jq -r '.ssh_keys[]')
IFS=$'\n'
for K in $KEYS; do
  if ! grep -q "$K" ~/.ssh/known_hosts; then
    echo "github.com $K" >>~/.ssh/known_hosts
    echo "updated ~/.ssh/known_hosts: github.com key: ${K:0:36}..."
  fi
done
# https://www.atlassian.com/git/tutorials/dotfiles
mkdir -p "$HOME/.config/"
DOTDIR="$HOME/.config/jpillora-dotfiles/"
function xgit() { git --git-dir="$DOTDIR" --work-tree="$HOME" "$@"; }
if [ -d "$DOTDIR" ]; then
  echo "===> 🟢 dotfiles repo already exists"
else
  echo "===> cloning dotfiles..."
  URL="git@github.com:jpillora/dotfiles.git"
  if ! git ls-remote "$URL" 2>/dev/null; then
    URL="https://github.com/jpillora/dotfiles.git"
  fi
  git clone --bare "$URL" $DOTDIR
  echo "===> 🟢 cloned into $DOTDIR"
  xgit config --local status.showUntrackedFiles no
fi
echo "===> dotfiles status..."
xgit status
echo "===> dotfiles checkout..."
xgit checkout main || echo "failed to checkout dotfiles, append .tmp to the files listed and rerun"
echo "===> 🟢 checkout dotfiles success"
# TODO, if fail, auto append .tmp to clash files
echo '===> restoring keys...'
mkdir -p ~/.ssh
curl -s https://github.com/jpillora.keys | tee ~/.ssh/authorized_keys
echo '===> restoring git config...'
git config --global user.name "Jaime Pillora"
git config --global user.email "dev@jpillora.com"
git config --global url."git@github.com:".insteadOf "https://github.com/"
if [ -f "$HOME/.ssh/id_ed25519.pub" ]; then
  git config --global gpg.format ssh
  git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
fi
# TODO, chsh and fish setup
echo '===> 🟢 restored dotfiles'
