#!/bin/bash
# Copyright: 2017 - 2018 - MIT License
# Source: https://github.com/envygeeks/devfiles
# Author: Jordon Bedwell
# --

[ "$DEBUG" = "true" ] && set -x
set -e

# --
trim() {
  echo "$@" | tr -s " " | \
    sed -e 's/^[[:space:]]*//g' | \
    sed -e 's/[[:space:]]$//g'
}

# --
[ -n "$1" ] && git config envygeeks.language "$1"
[ -n "$2" ] && git config envygeeks.external "$2"

# --
# Determine what we are working with.
# --

skip_if_exists=(Gemfile)
sync_language=$(git config envygeeks.language || echo "")
skip_if_external=(CONTRIBUTING.md CODE_OF_CONDUCT.md .github/codeowners)
skip_if_external+=(.github/issue_template.md .github/pull_request_template.md)
external=$(git config envygeeks.external || echo "false")
github_url=https://github.com/envygeeks/devfiles.git
copy_to=$PWD

# --
# Copies everything, except for what's to be skipped if
#   it happens to exist, into the current directory, so that
#   stays in sync with the parent.
# --

clone_dir=$(mktemp -d)
git clone $github_url "$clone_dir"
for d in $(trim global $sync_language); do
  cd "$clone_dir"

  [ ! -d "$d" ] && continue
  find "$d" -not -path "$d" -type f | while read f; do
    to=$(echo "$f" | sed -e "s/$d\///"); dir=$(dirname "$to")
    if [ "$dir" != "$d" ] && [ "$dir" != "." ]; then
      if [ ! -d "$copy_to/$dir" ]; then
        bash -xc "mkdir -p '$copy_to/$dir'"
      fi
    fi

    skip=false
    for sf in "${skip_if_exists[@]}"; do
      if [ "$to" = "$sf" ] && [ -f "$copy_to/$sf" ]; then
        skip=true
      fi
    done

    if [ "$skip" = "false" ] && [ "$external" = "true" ]; then
      for sf in "${skip_if_external[@]}"; do
        if [ "$to" = "$sf" ] && [ -f "$copy_to/$sf" ]; then
          skip=true
        fi
      done
    fi

    if [ "$skip" != "true" ]; then
      bash -xc "cp -L '$f' '$copy_to/$to'"
    fi
  done
done

rm -rf $clone_dir
