#!/bin/bash

# LXCF - LXC Facility
# copyright (C) 2014 FUJITSU LIMITED All Rights Reserved

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
# 02110-1301, USA.

# check root
if [ ${EUID:-${UID}} != 0 ]; then
    echo "error: Because you are not root, you cannot execute this command. "
    exit 1
fi

# check args
FLG_H=0
FLG_Q=1
FLG_L=0
QUEUE="Q-QUEUE"

while getopts hql OPT
do
  case $OPT in
    "h" ) FLG_H=1 ; FLG_Q=0 ; QUEUE="H-QUEUE" ;;
    "q" )           FLG_Q=1 ; QUEUE="Q-QUEUE" ;;
    "l" ) FLG_L=1 ; FLG_Q=0 ; QUEUE="L-QUEUE" ;;
  esac
done
shift `expr $OPTIND - 1`

# check args
if [ $# -ne 1 ]; then
	echo "usage: lxcf queue move [-h] [-q] [-l] UUID"
	exit 1
fi

UUID=$1

LINE=`cat /var/lib/lxcf/*queue | egrep "^$UUID"`

if [ $? -eq 1 ]; then
  echo "error: uuid" $UUID "is not exist"
  exit -1
fi

add_queue() {
	flock $1 echo $LINE >> $1
}

/usr/lib64/lxcf/lxcf-queue-cancel $UUID >& /dev/null

if [ $FLG_H -eq 1 ]; then
  add_queue /var/lib/lxcf/hqueue
elif [ $FLG_Q -eq 1 ]; then
  add_queue /var/lib/lxcf/qqueue
elif [ $FLG_L -eq 1 ]; then
  add_queue /var/lib/lxcf/lqueue
fi

echo "moved to" $QUEUE ":" $LINE

exit 0
