#!/bin/bash

# LXCF - LXC Facility
# Copyright (C) 2014 FUJITSU LIMITED

# 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} -ne 0 ] ; then
  echo "error: Because you are not root, you cannot execute this command."
  exit 1
fi

umask 022

LOGFILE=/var/log/lxcf/lxcf-messages

lsdir() {
  ls -f --ind=none $1 | sed '/^\.\{1,2\}$/d'
}

# break
exit 0

# If libvirtd.service is not effective, it does not do at all.
if [ -x /usr/bin/systemctl ] ; then
  if ! systemctl -q is-enabled libvirtd.service ; then
    exit 1
  fi
fi

# Nothing is done while sysgen, clone, and erase are operating.
ps -e -o comm | grep "^lxcf-\(sysgen\|clone\|erase\|restore\)$" >& /dev/null
if [ $? -eq 0 ]; then
  exit 1
fi

# force exit
exit 0

# A broken container is found, and it erases it.
virshcontainers=`virsh -c lxc:/// list --all | tail -n+3 | awk '{print $2}'`
containers=`/usr/lib64/lxcf/lxcf-list | tail -n+3 | cut -f1`
for i in $containers ; do
  if ! echo "$virshcontainers" | grep -q "^$i$" ; then
    TM=`LANG=C date "+%c"`

    ps -e -o comm | grep "^lxcf-\(sysgen\|clone\|erase\|restore\)$" >& /dev/null
    if [ $? -eq 0 ]; then
      exit 1
    fi

    flock $LOGFILE echo "### $TM COLLECTION BROKEN CONTAINER: $i ###" \
        >> $LOGFILE
    /usr/lib64/lxcf/lxcf-erase "$i" > /dev/null 2>&1
  fi
done

# Deletion of unnecessary file
for i in `lsdir /opt/lxcf`
do
	if [ x$i == x".work" ]; then
		continue;
	fi

	if [ -f /opt/lxcf/$i ]; then
		rm -f /opt/lxcf/$i
	fi
done

exit 0
