#!/usr/bin/python2.6
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2010  Joanna Rutkowska <joanna@invisiblethingslab.com>
#
# 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; either version 2
# of the License, or (at your option) any later version.
#
# 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.
#
#

from qubes.qubes import QubesVmCollection
from optparse import OptionParser;
import os

def main():
    usage = "usage: %prog [options] <vm-name>"
    parser = OptionParser (usage)
    parser.add_option ("-q", "--quiet", action="store_false", dest="verbose", default=True)
    parser.add_option ("--just-db", action="store_true", dest="remove_from_db_only", default=False,
                      help="Remove only from the Qubes Xen DB, do not remove any files")
    parser.add_option ("--force-root", action="store_true", dest="force_root", default=False,
                       help="Force to run, even with root privileges")
    (options, args) = parser.parse_args ()
    if (len (args) != 1):
        parser.error ("You must specify VM name!")
    vmname = args[0]

    qvm_collection = QubesVmCollection()
    qvm_collection.lock_db_for_writing()
    qvm_collection.load()
    vm = qvm_collection.get_vm_by_name(vmname)
    if vm is None or vm.qid not in qvm_collection:
        print "A VM with the name '{0}' does not exist in the system.".format(vmname)
        exit(1)

    if os.geteuid() == 0:
        print "*** Running this tool as root is strongly discouraged, this will lead you in permissions problems."
        if options.force_root:
            print "Continuing as commanded. You have been warned."
        else:
            print "Retry as unprivileged user."
            print "... or use --force-root to continue anyway."
            exit(1)

    if vm.is_template():
        dependent_vms = qvm_collection.get_vms_based_on(vm.qid)
        if len(dependent_vms) > 0:
            print "The following AppVMs use '{0}' as a template:".format(vmname)
            for vm in dependent_vms:
                print "{name:<12} (qid={qid})".format(qid=vm.qid, name=vm.name)
            print "Please remove those VMs first."
            exit (1)
        if qvm_collection.default_template_qid == vm.qid:
            qvm_collection.default_template_qid = None

    if vm.is_netvm():
       if qvm_collection.default_netvm_qid == vm.qid:
           qvm_collection.default_netvm_qid = None


    if vm.is_running():
        print "Cannot remove a running VM, stop it first"
        exit (1)

    if vm.installed_by_rpm and not options.remove_from_db_only:
        if options.verbose:
            print "This VM has been installed by RPM, use rpm -e <pkg name> to remove it!"
            exit (1)

    try:
        if options.verbose:
            print "--> Removing from Xen Storage..."
        vm.remove_from_xen_storage()
    except (IOError, OSError) as err:
        print "Warning: {0}".format(err)
        # Do not exit, perhaps the VM was not in the Xen store
        # so just remove it from Qubes DB

    try:
        if vm.installed_by_rpm:
            if options.verbose:
                print "--> VM installed by RPM, leaving all the files on disk"
        else:
            if options.verbose:
                print "--> Removing all the files on disk..."
            #TODO:  ask for confirmation, perhaps?
            vm.remove_from_disk()



    except (IOError, OSError) as err:
        print "Warning: {0}".format(err)
        # Do not exit, perhaps the VM files were somehow removed
        # so just remove it from Qubes DB


    qvm_collection.pop(vm.qid)
    qvm_collection.save()
    qvm_collection.unlock_db()

main()