#!/bin/bash
set -e

function do_pull(){
  msg "Reset and pull $branch"
  git reset --hard
  git checkout $branch
  git pull
}

function do_bundle(){
  msg "Bundling gems, npm, and bower"
  bundle install --deployment --without development test
  npm install --production
  ./node_modules/bower/bin/bower install --production
}

function do_assets(){
  msg "Clean Assets"
  RAILS_ENV=production bundle exec rake assets:clean

  msg "Precompiling Assets"
  RAILS_ENV=production bundle exec rake assets:precompile
}

function do_migrate(){
  if [ $app_env == "sandbox" ]; then
    msg "SANDBOX: rebuilding db with fixtures"
    RAILS_ENV=production \
    DISABLE_DATABASE_ENVIRONMENT_CHECK=1 \
    bundle exec rake db:drop db:setup db:migrate db:fixtures:load
  else
    msg "DB Migrate PRODUCTION"
    RAILS_ENV=production bundle exec rake db:migrate
  fi
}

function quick(){
  do_pull
  app_restart
}

function full(){
  do_pull
  do_bundle
  do_migrate
  do_assets
  app_restart
}

function assets(){
  do_pull
  do_assets
  app_restart
}

function migration(){
  do_pull
  do_migrate
  app_restart
}

function app_restart(){
  touch tmp/restart.txt
  msg "App Restarted"
}

function msg(){
  if [ ${#@} != 0 ]; then
    tput setaf 2
    echo $*
    tput sgr0
  fi
}

function helps {
  tput setaf 3
  echo "SkillApp Deploy-er
  A simple deploy helper meant to be ran from a server ssh session.
    -q, --quick          : pull, restart
    -f, --full           : pull, bundle, migrate (rebuild sandbox db), asset clean/precompile, restart
    -a, --with-assets    : pull, precompile, restart
    -m, --with-migration : pull, migrate (rebuild sandbox db), restart
    --restart            : just restart the app

  "
  tput sgr0
}

###########################################
###########################################
###########################################

if [ ! -f ".deploy.conf" ]; then
  msg "Missing .deploy.conf -- check out .deploy.conf.sample"
else
  IFS="="
  while read -r name value; do
    case $name in
      'branch') export branch="${value//\"/}" ;;
      'app_env') export app_env="${value//\"/}" ;;
    esac
  done < .deploy.conf

  if [ ! -d ".git" ]; then
    msg "No git repo found. You must call this script from the application root."
    helps
  else
    if [ ${#@} != 1 ]; then
      helps
    else
      case $1 in
        '-a' ) assets ;;
        '--with-assets' ) assets ;;
        '-q' ) quick ;;
        '--quick' ) quick ;;
        '-f') full;;
        '--full') full;;
        '-m') migration;;
        '--with-migration') migration;;
        '--restart') app_restart;;
        *) helps ;;
      esac
    fi
  fi
fi
