#!/bin/bash

set -eux

source ~/overcloudrc
# TODO(bnemec): Hard-coding this to . for now because it's tricky to extract
# the value from the new conf file when not using oslo.config.
IMAGE_PATH='.'

# tripleo os-adduser -p $OVERCLOUD_DEMO_PASSWORD demo demo@example.com

if ! glance image-show user 2>&1 1>/dev/null; then
	glance image-create --name user --is-public True --disk-format qcow2 \
	    --container-format bare --file $IMAGE_PATH/fedora-user.qcow2
fi

tripleo wait_for 30 10 nova service-list --binary nova-compute 2\>/dev/null \| grep 'enabled.*\ up\ '

tripleo wait_for 30 10 neutron agent-list -f csv -c alive -c agent_type -c host \| grep "\":-).*Open vSwitch agent.*compute\""

# source $TRIPLEO_ROOT/overcloudrc-user

NET_ID=$(neutron net-list -f csv --quote none | grep default-net | cut -d, -f1)

if ! nova keypair-show default 2>/dev/null; then
	tripleo user-config
fi

nova boot --poll --key-name default --flavor m1.demo --image user --nic net-id=$NET_ID demo

sleep 3

PRIVATEIP=$(nova list | grep demo | awk -F"default-net=" '{print $2}' | awk '{print $1}')

tripleo wait_for 10 5 neutron port-list -f csv -c id --quote none \| grep id
PORT=$(neutron port-list | grep $PRIVATEIP | cut -d'|' -f2)
FLOATINGIP=$(neutron floatingip-create ext-net --port-id "${PORT//[[:space:]]/}" | awk '$2=="floating_ip_address" {print $4}')

SECGROUPID=$(nova secgroup-list | grep default | cut -d ' ' -f2)
neutron security-group-rule-create $SECGROUPID --protocol icmp \
    --direction ingress --port-range-min 8 || true
neutron security-group-rule-create $SECGROUPID --protocol tcp \
    --direction ingress --port-range-min 22 --port-range-max 22 || true

# Must use sudo when calling ping
# See https://bugzilla.redhat.com/show_bug.cgi?id=1144149
tripleo wait_for 30 10 sudo -E ping -c 1 $FLOATINGIP

tripleo wait_for 10 10 nova list \| grep ACTIVE

ssh-keygen -R $FLOATINGIP
tripleo wait_for 30 10 ssh -o BatchMode=yes -o StrictHostKeyChecking=no fedora@$FLOATINGIP ls
tripleo wait_for 30 10 ssh -o BatchMode=yes -o StrictHostKeyChecking=no -tt fedora@$FLOATINGIP systemctl status cloud-final


echo Compute test successful!


CINDER_VOLUME_ID=$(cinder create 1 | grep " id " | awk '{print $4}')

tripleo wait_for 10 3 cinder list \| grep available

nova volume-attach demo $CINDER_VOLUME_ID

tripleo wait_for 30 10 ssh -o StrictHostKeyChecking=no fedora@$FLOATINGIP ls /dev/vdb

ssh -tt fedora@$FLOATINGIP sudo fdisk /dev/vdb <<EOF
o
w
EOF

ssh -tt fedora@$FLOATINGIP sudo fdisk /dev/vdb <<EOF
n
p
1


w
EOF

ssh -tt fedora@$FLOATINGIP sudo mkfs.ext4 /dev/vdb1

ssh -tt fedora@$FLOATINGIP sudo mount /dev/vdb1 /mnt
ssh -tt fedora@$FLOATINGIP sudo umount /mnt


echo Cinder test successful!


tmpfile=$(mktemp)
echo SWIFTTEST > $tmpfile

swift upload test $tmpfile
swiftfile=$(swift list test)

swift download --output $tmpfile-1 test $swiftfile

if [ ! "$(cat $tmpfile-1)" == "SWIFTTEST" ]; then
    echo Swift test failed!
fi

swift delete test


echo Swift test successful!
