#!/bin/bash
#
# Test the PHP image in OpenShift.
#
# IMAGE_NAME specifies a name of the candidate image used for testing.
# The image has to be available before this script is executed.
#

THISDIR=$(dirname ${BASH_SOURCE[0]})

source ${THISDIR}/test-lib.sh
source ${THISDIR}/test-lib-openshift.sh

# change the branch to a different value if a new change in the example
# app needs to be tested
BRANCH_TO_TEST=master

set -eo nounset

test -n "${IMAGE_NAME-}" || false 'make sure $IMAGE_NAME is defined'
test -n "${VERSION-}" || false 'make sure $VERSION is defined'
test -n "${OS-}" || false 'make sure $OS is defined'
istag="php:$VERSION"

function test_file_upload() {
  local image_name=$1
  local service_name=${image_name##*/}
  local app="https://github.com/openshift-qe/openshift-php-upload-demo"
  local ip=""

  echo "Running file upload test for: $image_name"
  ct_os_new_project
  ct_os_upload_image "$image_name" "$istag"

  ct_os_deploy_s2i_image "$istag" "$app" --name "${service_name}"
  ct_os_wait_pod_ready "$service_name" 60

  # Wait until the app is prepared to receive files
  ip=$(ct_os_get_service_ip "$service_name")
  curl "$ip:8080" 2>/dev/null | grep -q "OpenShift File Upload Demonstration"

  # Upload a file into the pod using the php app
  curl -F fto=@README.md "$ip:8080/upload.php" &>/dev/null
  ct_os_run_in_pod "$(ct_os_get_pod_name "$service_name")" ls uploaded/README.md >/dev/null

  ct_os_delete_project
}

ct_os_cluster_up

# test local app
ct_os_test_s2i_app ${IMAGE_NAME} "https://github.com/sclorg/s2i-php-container.git" ${VERSION}/test/test-app "Test PHP passed"

ct_os_test_s2i_app ${IMAGE_NAME} "https://github.com/sclorg/cakephp-ex.git#${BRANCH_TO_TEST}" . 'Welcome to your CakePHP application on OpenShift'

# cakephp template does not work with version 5.6
if [[ "${VERSION}" > "5.6" ]] ; then
  ct_os_test_template_app ${IMAGE_NAME} \
                        https://raw.githubusercontent.com/sclorg/cakephp-ex/${BRANCH_TO_TEST}/openshift/templates/cakephp.json \
                        php \
                        'Welcome to your CakePHP application on OpenShift' \
                        8080 http 200 "-p SOURCE_REPOSITORY_REF=${BRANCH_TO_TEST} -p SOURCE_REPOSITORY_URL=https://github.com/sclorg/cakephp-ex.git -p PHP_VERSION=${VERSION} -p NAME=php-testing"
fi

# test image update with s2i
case "$OS" in
  rhel7) old_image=rhscl/php-${VERSION/./}-rhel7 ;;
# Fedora image isn't in registry yet
#  fedora) old_image=${IMAGE_NAME/localhost\//}
  *) old_image=centos/php-${VERSION/./}-centos7 ;;
esac
ct_os_test_image_update "$IMAGE_NAME" "${old_image}" "$istag" \
                        'ct_test_response "http://<IP>:8080" "200" "Test PHP passed"' \
                        "$istag~https://github.com/sclorg/s2i-php-container.git" \
                        --context-dir="$VERSION/test/test-app"

test_file_upload "$IMAGE_NAME"
