#!/usr/bin/env bash

set -e

if [ `uname` == 'Linux' ]; then
  if [ -f /etc/lsb-release -o -d /etc/lsb-release.d ]; then
    OS=`lsb_release -i -s | tr '[:upper:]' '[:lower:]'`
  else
    OS=`ls -d /etc/[A-Za-z]*[_-][rv]e[lr]* | grep -v "lsb" | cut -d'/' -f3 | cut -d'-' -f1 | cut -d$'\n' -f1`
  fi
else
  OS=`uname | tr '[:upper:]' '[:lower:]'`
fi
CONFIG="install.conf.yaml"
DOTBOT_DIR="vendor/dotbot"
DOTBOT_BIN="bin/dotbot"
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BOOTSTRAP_SCRIPT="${BASE_DIR}/os/${OS}.conf.yaml"

cd "${BASE_DIR}"
git -C "${DOTBOT_DIR}" submodule sync --quiet --recursive
git submodule update --init --recursive "${DOTBOT_DIR}"

if [[ -f "${BOOTSTRAP_SCRIPT}" ]]; then
  cmd=("${BASE_DIR}/${DOTBOT_DIR}/${DOTBOT_BIN}" -d "${BASE_DIR}" -c "${BOOTSTRAP_SCRIPT}")
  "${cmd[@]}"
else
  echo "Unsupported ${OS} or ${BOOTSTRAP_SCRIPT} not found."
fi

echo "Running global configuration"
"${BASE_DIR}/${DOTBOT_DIR}/${DOTBOT_BIN}" -d "${BASE_DIR}" -c "${CONFIG}" "${@}"
