#!/usr/bin/env bash
#
# Copyright 2013 Red Hat
# All Rights Reserved.
#
# 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.

SCRIPT_NAME=$(basename $0)

LIBVIRT_VOL_POOL=${LIBVIRT_VOL_POOL:-"default"}

function show_options() {
    echo "Usage: $SCRIPT_NAME [-n NUM]"
    echo
    echo "Cleanup vm state left behind by previous runs"
    echo
    echo "    -n                     -- Test environment number to clean up."
    echo
    echo "If provided, NUM is the environment number to be cleaned up."
    echo "If not provided, the default environment will be cleaned."
    exit 1
}

NUM=

TEMP=$(getopt -o h,n: -n $SCRIPT_NAME -- "$@")
if [ $? != 0 ] ; then show_options; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
  case "$1" in
    -h) show_options ;;
    -n) NUM="$2" ; shift 2 ;;
    --) shift ; break ;;
    *) echo "Error: unsupported option $1." ; show_options ;;
  esac
done

SEED_NAME=seed
BRIDGE_NAME=

if [ -n "$NUM" ]; then
  SEED_NAME="seed_${NUM}"
  BRIDGE_NAME="brbm${NUM}"
fi

BAREMETAL_REGEX="baremetal${BRIDGE_NAME}"
for NAME in $(sudo virsh list --name --all | grep "^\($SEED_NAME\|${BAREMETAL_REGEX}_.*\)$"); do
  sudo virsh destroy $NAME
  sudo virsh undefine --managed-save --remove-all-storage $NAME
done

for NAME in $(sudo virsh vol-list $LIBVIRT_VOL_POOL 2>/dev/null | grep /var/ | awk '{print $1}' | grep "^\($SEED_NAME\|$BAREMETAL_REGEX\)" ); do
  sudo virsh vol-delete --pool $LIBVIRT_VOL_POOL $NAME
done
