1#!/usr/bin/env bash
2
3set -eo pipefail
4
5script_dir="$(dirname "$0")"
6
7shopt -s dotglob
8
9# an optional template file will be synced only if the target file is present in the file system,
10# and its content contains the string `@generated`.
11OPTIONAL_TEMPLATE_FILES=(
12  # add a relative file path from `templates/` for each new optional file
13  "scripts/with-node.sh"
14)
15
16# returns relative file paths inside a given directory without the leading "./".
17# usage: get_relative_files "/path/to/dir"
18get_relative_files() {
19  pushd $1 > /dev/null
20  local files=$(find . -type f | cut -c 3-)
21  popd > /dev/null
22  echo $files
23}
24
25
26# syncs the source file if the target file is missing or the existing file contains `@generated`.
27# usage: sync_file_if_missing "/path/source_path" "/path/target_path"
28sync_file_if_missing() {
29  local source=$1
30  local target=$2
31  # echo "sync_file_if_missing $source -> $target"
32  if [ ! -f "$target" ] || grep --quiet "@generated" "$target"; then
33    rsync --checksum "$source" "$target"
34  fi
35}
36
37# syncs the source file if the target file is present in the file system and its content contains `@generated`.
38# usage: sync_file_if_present "/path/source_path" "/path/target_path"
39sync_file_if_present() {
40  local source=$1
41  local target=$2
42  # echo "sync_file_if_present $source -> $target"
43  if [ -f "$target" ] && grep --quiet "@generated" "$target"; then
44    rsync --checksum "$source" "$target"
45  fi
46}
47
48# check if a file is listed in `OPTIONAL_TEMPLATE_FILES`.
49# usage: if is_optional_file "path/to/file"; then ... fi
50is_optional_file() {
51  local file=$1
52  for optional_file in "${OPTIONAL_TEMPLATE_FILES[@]}"; do
53    if [ "$file" = "$optional_file" ]; then
54      true
55      return
56    fi
57  done
58
59  false
60  return
61}
62
63#
64# script main starts from here
65#
66
67"$script_dir/expo-module-readme"
68
69template_files=$(get_relative_files "$script_dir/../templates")
70for template_relative_file in $template_files; do
71  if is_optional_file "$template_relative_file"; then
72    sync_file_if_present "$script_dir/../templates/$template_relative_file" "$template_relative_file"
73  else
74    sync_file_if_missing "$script_dir/../templates/$template_relative_file" "$template_relative_file"
75  fi
76done
77