#!/bin/bash

source script/common.sh

LOG="$(pwd)/log/canvas_update.log"

# TODO: improve usage / help
function usage {
  echo "usage: canvas_update [-qhv] [-n phase]"
}

function bad_usage {
  usage
  exit 1
}

# TODO: moar tips plz
function tips {
  echo "Tips:"
  echo "  - 'bundle exec guard': auto-compiles JS files while developing"
  echo "  - 'script/delayed_job run': run delayed jobs in the foreground"
}

function update_canvas {
  ensure_in_canvas_root_directory
  intro_message "Canvas Update"

  if [[ -z "$SKIP_CODE" ]] ; then
    update_plugins
    rebase_canvas
  fi

  if [[ -z "$SKIP_DEPS" ]] ; then
    bundle_install_with_check
    install_node_packages
  fi

  if [[ -z "$SKIP_DATA" ]] ; then
    rake_db_migrate_dev_and_test

    # skip if QUICK_MODE
    if ! $QUICK_MODE; then
      compile_assets
    fi
  fi

  # We should only display tips if this script is being run standalone
  if [[ -n "$SKIP_CODE" && -n "$SKIP_DEPS" && -n "$SKIP_DATA" ]] ; then
    tips
  fi
}

# default options
PERFORM_UPDATE=true
QUICK_MODE=false

# parse options
# http://www.tldp.org/LDP/abs/html/internal.html#EX33
while getopts ":qhn:v" Option
do
  case $Option in
    q )
      echo "Quick mode enabled (assumes you have guard running and don't want to generate docs)"
      QUICK_MODE=true;;
    h )
      usage
      exit 0;;
    n )
      case $OPTARG in
        code )
          SKIP_CODE=true;;
        deps )
          SKIP_DEPS=true;;
        data )
          SKIP_DATA=true;;
        assets )
          QUICK_MODE=true;;
        * )
          bad_usage;;
      esac
      echo "Skipping $OPTARG";;
    v )
      set -x
      LOG=/dev/stdout;;
    * )
      echo "Sorry, -$OPTARG is not a valid option!"
      bad_usage;;
  esac
done

if [ "$PERFORM_UPDATE" == "true" ]; then
  trap print_results INT TERM EXIT
  create_log_file
  update_canvas
fi
