#!/usr/bin/env bash
# Bootstrap this machine. Picks the host layer by hostname; refuses rather than
# guessing if there isn't one, because a silent fallback to "base only" looks
# like success and leaves half the machine unconfigured.
set -euo pipefail

BASEDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DOTBOT_DIR="dotbot"
DOTBOT_BIN="bin/dotbot"
# uname -n, not hostname(1): the latter comes from inetutils and is absent on
# a minimal Arch install. The NAS had no hostname binary at all.
HOST="${DOTFILES_HOST:-$(uname -n | tr '[:upper:]' '[:lower:]')}"
HOSTCONF="meta/hosts/${HOST}.conf.yaml"

cd "${BASEDIR}"

if [[ ! -f "${HOSTCONF}" ]]; then
  echo "install: no host config for '${HOST}'." >&2
  echo "         expected ${HOSTCONF}" >&2
  echo "         known hosts: $(ls meta/hosts/ | sed 's/\.conf\.yaml//' | tr '\n' ' ')" >&2
  echo "         for a new machine, copy the closest one and edit." >&2
  exit 1
fi

# Git cannot represent an empty directory, so a link whose source contains no
# files disappears on clone and dotbot fails with "Nonexistent target". Catch
# it here rather than on someone else's machine.
missing=0
while read -r src; do
  [[ -e "${src}" ]] || { echo "install: link source missing from the repo: ${src}" >&2; missing=1; }
done < <(grep -hoE '^\s+~[^:]*:\s+\S+' meta/base.conf.yaml "${HOSTCONF}" | awk '{print $NF}')
(( missing )) && { echo "install: refusing to run with missing sources." >&2; exit 1; }

git submodule update --init --recursive "${DOTBOT_DIR}"

echo "==> base"
"${DOTBOT_DIR}/${DOTBOT_BIN}" -d "${BASEDIR}" -c meta/base.conf.yaml "${@}"
echo "==> host: ${HOST}"
"${DOTBOT_DIR}/${DOTBOT_BIN}" -d "${BASEDIR}" -c "${HOSTCONF}" "${@}"

if [[ ! -r "${HOME}/.secrets.zsh" ]]; then
  echo
  echo "note: ~/.secrets.zsh does not exist yet."
  echo "      cp common/zsh/secrets.zsh.example ~/.secrets.zsh && chmod 600 ~/.secrets.zsh"
fi
if [[ -d "hosts/${HOST}/sbin" ]] && [[ -n "$(ls -A "hosts/${HOST}/sbin" 2>/dev/null)" ]]; then
  echo
  echo "note: this host has system scripts needing root:"
  echo "      sudo install -m755 hosts/${HOST}/sbin/* /usr/local/bin/"
fi
if [[ -d "hosts/${HOST}/etc" ]]; then
  echo
  echo "note: this host has system config needing root:"
  echo "      sudo cp -r hosts/${HOST}/etc/. /etc/ && sudo systemctl daemon-reload"
fi
