#!/usr/bin/env bash

# To implement this command, edit the "Command implementation" section below. 

# Usage
# -----

# Comments prefixed with `#/` are managed by stubbs.
# The `command` and `usage` comments describe the command
# and show its options.
# 
#/ command: accept:upgrade: "Tests upgrade path for Deis"
#/ usage: rerun accept:upgrade  --provider <vagrant>  --from <> [ --to <master>] [ --skip-cleanup <false>]  --upgrade-style <graceful> 

# Load common functions
# ---------------------

# Load the function library for this module.
# This loads rerun functions, too.
. $RERUN_MODULE_DIR/lib/functions.sh upgrade || { 
  echo >&2 "Failed loading function library." ; exit 1 ; 
}

# Error handling
# ---------------

# This script is designed to _fail-fast_.

# Trap errors and exit. The call to `rerun_die` will print the
# the error message and exit with the error command exit status. 

trap 'rerun_die $? "*** command failed: tests:upgrade. ***"' ERR

# Run [set] `nounset` to treat unset variables as errors. Set [pipefail]
# so a pipeline return status is the value of the last 
# (rightmost) command to exit with non-zero status.
#
# [set]: http://ss64.com/bash/set.html
# [pipefail]: http://www.gnu.org/software/bash/manual/html_node/Pipelines.html

set -o nounset -o pipefail

# Command variables
# -----------------

# This command script can access the following variables
# declared by `rerun` or by the option parser function.

#/ rerun-variables: RERUN, RERUN_VERSION, RERUN_MODULES, RERUN_MODULE_DIR
#/ option-variables: PROVIDER FROM TO SKIP_CLEANUP UPGRADE_STYLE

# The `rerun_options_parse` function processes the command line
# arguments. Each accepted command line flag results in setting 
# one the corresponding option variables.

rerun_options_parse "$@"

trap destroy-cluster EXIT

# Command implementation
# ----------------------

function healthcheck {
  rerun_log "Running healthcheck of previously deployed app.."

  if ! curl -s "http://testing.${DEIS_TEST_DOMAIN}" | grep -q "Powered by Deis"; then
    rerun_log error "Failed to pass healthcheck."
    return 1
  else
    rerun_log info "Healthcheck succeeded."
    return 0
  fi
}

setup-provider "${PROVIDER}"
setup-upgrader "${UPGRADE_STYLE}"

setup-provider-dependencies

destroy-cluster

setup-clients "${FROM}"

make discovery-url

create-cluster

deploy-deis "${FROM}"

make test-smoke

upgrade-deis "${FROM}" "${TO}"

healthcheck
