#!/usr/bin/env bash
set -euo pipefail
shopt -s nullglob

if [ $# -eq 0 ]; then
  echo "expected a service name as an argument"
  exit 1
fi

if [[ "$1" == help ]] ; then
  echo ""
  echo "  template/new.sh SERVICE"
  echo ""
  cd "$(dirname "$0")"
  cat README.md | awk '{ print "  " $0 }'
  exit 0
fi

service="$(basename "$1")"


set -x
mkdir -p "$service"
cd "$service"

mkdir -p service
mkdir -p cmd/server
mkdir -p bin
mkdir -p test
mkdir -p worker
mkdir -p db/entity
mkdir -p proto/output/statik
set +x

function if_not_exists(){
  given="$1"
  shift
  template="../template/$given"
  if ! [[ -f "$template" ]] && ! [[ -d "$template" ]] ; then
	  echo "does not exist: $template"
	  exit 1
  fi
  dir=$(dirname "$given")
  file=$(basename "$given")
  if ! [[ -z "$dir" ]] ; then
    mkdir -p "$dir"
  fi
  [[ -L "$given" ]] || [[ -f "$given" ]] || {
    echo "$@"
    "$@"
  }
  return $?
}

function link_if_not_exists(){
  template="../template/$1"
  if_not_exists "$1" ln -s -r "$template" "$1"
}

if_not_exists Makefile /bin/sh -c "echo 'include ../template/Makefile' > Makefile"
link_if_not_exists Justfile
link_if_not_exists .gitignore

link_if_not_exists proto/Makefile
link_if_not_exists proto/swagger-ui
test -f proto/output/statik/bootstrap.go || /bin/sh -c "echo 'package statik' > proto/output/statik/bootstrap.go"
test -f proto/output/service.proto || /bin/sh -c "echo 'package $service' > proto/output/bootstrap.go"

link_if_not_exists conf/revive.toml

link_if_not_exists build/base/build.sh

link_if_not_exists build/migrate/build.sh

link_if_not_exists build/seed/build.sh

for f in ../template/scripts/* ; do
  link_if_not_exists "scripts/$(basename $f)"
done

echo "done"
