#!/usr/bin/env bash

# If GENERATED_DIR is not ignored, it won't survive 'git clean -fd'
#
ignore_generated_dir() {
  if [ $(egrep -c -e "^$GENERATED_DIR/*" .gitignore) = 0 ]
  then
    echo "$GENERATED_DIR/*" >> .gitignore
    __exec "git commit -a -m 'Ignoring $GENERATED_DIR'"
  fi
}

store_current_git_branch() {
  local git_head="$(git symbolic-ref HEAD)"
  echo "${git_head##*/}" > /tmp/deliver_current_git_branch
}

move_generated_files_to_root() {
  __exec "mv $GENERATED_DIR/* ."
  __exec "rm -fr $GENERATED_DIR"

  if [ -e "$APP.html" ] && [ ! -e "index.html" ]
  then
    __exec "cp $APP.html index.html"
  fi
}

reset_git_head() {
  __exec "git symbolic-ref HEAD refs/heads/$GENERATED_BRANCH"
  __exec "rm .git/index"
  __exec "ls -a $ORIGIN_DIR | egrep -v -e \"\.$|\.git$|$GENERATED_DIR\" | while read resource; do rm -fr \"\$resource\"; done"
}

# If GENERATE_BIN is set, it will run it,
# otherwise it will default to the standard rocco command.
#
generate() {
  status "Generating content"

  ignore_generated_dir

  CURRENT_GIT_BRANCH="$(git symbolic-ref HEAD)"

  store_current_git_branch

  if [ -n "$GENERATE_CMD" ]
  then
    __exec "$GENERATE_CMD"
  elif [ -n "$ROCCO_FILES" ]
  then
    set -f # disables file globbing
    __exec "bundle exec rocco -o $GENERATED_DIR $ROCCO_FILES"
    set +f # enables file globbing
  else
    error "
You must define one of the following:
* GENERATE_CMD - a bash function or an executable file which will generate the html files
* ROCCO_FILES - the source files that you want running through rocco\n"
  fi

  reset_git_head
  move_generated_files_to_root

  __exec "git add ."
}

set_revision_to_generated() {
  REVISION=$(git rev-parse $GENERATED_BRANCH)
}

commit_generated() {
  status "Committing generated content"
  __exec "git commit -a -m 'Generated with deliver'"
  set_revision_to_generated
}

generated_cleanup() {
  __exec "git checkout -f $(cat /tmp/deliver_current_git_branch)"
  __exec "rm /tmp/deliver_current_git_branch"
}
