#!/usr/bin/env bash

# Exit on first failing command.
set -e

# Exit on unset variable.
set -u

# Echo commands before executing them, by default to stderr.
set -x

# Update dev scripts in a directory to the latest version available in the
# dev-scripts repo.

readonly TARGET_DEV_SCRIPTS="${PWD}/dev-scripts"
if [[ ! -d "${TARGET_DEV_SCRIPTS}" ]]; then
  echo "No dev-scripts directory found"
  echo "Run this from a project with a dev-scripts directory."
  exit 1
fi

cd "$(mktemp --directory)"

git clone https://github.com/mtlynch/dev-scripts .
readonly GOLDEN_DEV_SCRIPTS="${PWD}/dev-scripts"

for f in "${GOLDEN_DEV_SCRIPTS}/"*; do
  FILENAME="$(basename "${f}")"
  TARGET_SCRIPT="${TARGET_DEV_SCRIPTS}/${FILENAME}"
  if [[ ! -f "${TARGET_SCRIPT}" ]]; then
    continue
  fi
  GOLDEN_SCRIPT="${GOLDEN_DEV_SCRIPTS}/${FILENAME}"
  cp "${GOLDEN_SCRIPT}" "${TARGET_SCRIPT}"
  chmod +x "${TARGET_SCRIPT}"
done
