#!/bin/bash

# Copyright (c) 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This program expects to be run by tox in a virtual python environment
# so that it does not pollute the host development system

GREEN='\e[0;32m'
RED='\e[0;31m'
NC='\e[0m' # No Color

print()
{
    echo -e "\n${GREEN}$*${NC}"
}

sudo_env()
{
    sudo bash -c "PATH=$PATH $*"
}

cleanup()
{
    print "Cleaning SoF mount point"
    sudo rm -rf /mnt/swiftonfile/test/* > /dev/null 2>&1
    sudo setfattr -x user.swift.metadata /mnt/swiftonfile/test > /dev/null 2>&1
}

fail()
{
    cleanup
    echo -e "\n${RED}$1${NC}"
    exit 1
}

### MAIN ###

print """
Before proceeding forward, please make sure you already have:
1. SAIO deployment.
2. XFS/GlusterFS mounted at /mnt/swiftonfile/test
3. Added swiftonfile policy section to swift.conf file.
   Example:

       [storage-policy:3]
       name = swiftonfile
       policy_type = replication
       default = yes

   Added sof_constraints middleware in proxy pipeline

       [pipeline:main]
       pipeline = catch_errors sof_constraints cache proxy-server

       [filter:sof_constraints]
       use = egg:swiftonfile#sof_constraints
       policies=swiftonfile

4. Copied etc/object-server.conf-swiftonfile to /etc/swift/object-server/5.conf

5. Generated ring files for swiftonfile policy.
   Example: for policy with index 3

       swift-ring-builder object-3.builder create 1 1 1
       swift-ring-builder object-3.builder add r1z1-127.0.0.1:6050/test 1
       swift-ring-builder object-3.builder rebalance

6. Started memcached and swift services.
"""

prompt=true
if [ "$1" == "-q" ]; then
    prompt=false
fi

if $prompt; then
    read -p "Continue ? " -r
    if [[ $REPLY =~ ^[Nn]$ ]]
    then
        exit 1
    fi
fi

export SWIFT_TEST_CONFIG_FILE=/etc/swift/test.conf

mkdir functional_tests_result > /dev/null 2>&1

print "Runnning functional tests"
nosetests -v --exe \
	--with-xunit \
	--xunit-file functional_tests_result/swiftonfile-generic-functional-TC-report.xml \
    --with-html-output \
    --html-out-file functional_tests_result/swiftonfile-generic-functional-result.html \
    test/functional || fail "Functional tests failed"
cleanup
exit 0