#!/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 "Stopping memcached"
    sudo service memcached stop
    print "Stopping swift sevices"
    sudo_env swift-init main stop
    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
    print "Invoking SAIO's resetswift script"
    resetswift
}

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

### MAIN ###

print """
Before proceeding forward, please make sure you already have:
1. SAIO deployment. (with resetswift and remakerings script)
2. XFS/GlusterFS mounted at /mnt/swiftonfile/test
"""

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

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

print "Invoking SAIO's resetswift script"
resetswift

print "Invoking SAIO's remakerings script"
remakerings

print "Copying conf files into /etc/swift. This will replace swift.conf and test.conf"
\cp etc/object-server.conf-swiftonfile /etc/swift/object-server/5.conf
\cp test/functional/conf/swift.conf /etc/swift/swift.conf
\cp test/functional/conf/test.conf /etc/swift/test.conf

print "Generating additional object-rings for swiftonfile SP"
cd /etc/swift
swift-ring-builder object-2.builder create 1 1 1
swift-ring-builder object-2.builder add r1z1-127.0.0.1:6050/test 1
swift-ring-builder object-2.builder rebalance
cd -

export SWIFT_TEST_CONFIG_FILE=/etc/swift/test.conf

print "Starting memcached"
sudo service memcached start || fail "Unable to start memcached"
print "Starting swift services"
sudo_env swift-init main start || fail "Unable to start swift"

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