#!/bin/bash
# chkconfig:
# description:
#
#: Script Name	: changecase-vmname.sh
#: Version	: 1.0.1
#: Author	: Matthew Mattoon - http://blog.allanglesit.com
#: Date Created	: January 26, 2013
#: Date Updated	: February 20, 2013
#: Description	: Changes case of all Oracle VM 3.x VMs to either upper or lower case. 
#: Examples	: changecase-vmname.sh -c CASE -m OVMMANAGER -p PORT -u USER
#: 		: changecase-vmname.sh -c lower -m ovmserver.localdomain

usage()
{
cat << EOF
usage: $0 options

This script allows you to change case on all OVM 3.x VMs to either uppercase or lowercase.

OPTIONS:
   -h	Show this message
   -c	The preferred case for all VMs (required). upper or lower
   -m	OVM 3.x Manager Server (required).
   -p	OVM 3.x Manager Port (default: 10000).
   -u	OVM 3.x Manager User (default: admin).
EOF
}

while getopts "hc:m:pu" OPTION
 do
  case $OPTION in
   h) usage; exit 1;;
   c) case=$OPTARG;;
   m) ovmmgr=$OPTARG;;
   p) ovmport=$OPTARG;;
   u) ovmuser=$OPTARG;;
   ?) usage; exit 1;;
  esac
 done

if [[ -z $case ]] || [[ -z $ovmmgr ]]
 then
  usage
  exit 1
fi

if [ $case != "lower" -a $case != "l" -a $case != "upper" -a $case != "u" ]
 then
  usage
  exit 1
fi

if [[ -z $ovmuser ]]
 then
  ovmuser=admin
fi

if [[ -z $ovmport ]]
 then
  ovmport=10000
fi

if [ $case = "lower" -o $case = "l" ]
 then
  trcase="'[:upper:]' '[:lower:]'"
fi

if [ $case = "upper" -o $case = "u" ]
 then
  trcase="'[:lower:]' '[:upper:]'"
fi


for i in `ssh -p $ovmport $ovmuser@$ovmmgr "list vm" | grep -v 'OVM>\|Command:\|Status:\|Time:\|Data:' | sed 's/  /:/g'`
 do
  id=`echo $i | cut -d ":" -f 3`
  echo -n "Examining $id...  "
  vmname=`ssh -p $ovmport $ovmuser@$ovmmgr "show vm id=$id" | grep -v 'OVM>\|Command:\|Status:\|Time:\|Data:' | grep "Name" | sed 's/ = /=/' | cut -d = -f 2`
  newvmname=`echo $vmname | tr $trcase`
  if [ $vmname != $newvmname ]
   then
    echo "Renaming $vmname to $newvmname"
    ssh -p $ovmport $ovmuser@$ovmmgr edit vm id=$id name="$newvmname" | grep "Status:"
   else
    echo "Rename not required"
  fi
 done


