#!/usr/bin/python
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2012  Marek Marczykowski <marmarek@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 subprocess
import sys
import re

def do_list(vm):
    max_len = 0
    for s in vm.services.keys():
        max_len = max(max_len, len(s))
    fmt="{{0:<{0}}}: {{1}}".format(max_len)

    for s in vm.services.keys():
        print fmt.format (s, "Enabled" if vm.services[s] else "Disabled")


def main():
    usage =  "usage: %prog <vm-name> [action] [service]\n"
    parser = OptionParser (usage)
    parser.add_option ("-l", "--list", dest="do_list", action="store_true", default=True,
            help="List services (default action)")
    parser.add_option ("-e", "--enable", dest="set_enable", action="store_true", default=False,
            help="Enable service")
    parser.add_option ("-d", "--disable", dest="set_disable", action="store_true", default=False,
            help="Disable service")
    parser.add_option ("-D", "--default", dest="set_default", action="store_true", default=False,
            help="Reset service to its default state (remove from the list)")

    (options, args) = parser.parse_args ()
    if (len (args) < 1):
        parser.error ("You must specify VM name!")
    vmname = args[0]
    args = args[1:]

    if options.set_enable or options.set_disable or options.set_default:
        if (len(args) < 1):
            parser.error("You must specify service name!")
        options.do_list = False

    qvm_collection = QubesVmCollection()
    if options.do_list:
        qvm_collection.lock_db_for_reading()
        qvm_collection.load()
        qvm_collection.unlock_db()
    else:
        qvm_collection.lock_db_for_writing()
        qvm_collection.load()

    vm = qvm_collection.get_vm_by_name(vmname)
    if vm is None:
        print >> sys.stderr, "A VM with the name '{0}' does not exist in the system.".format(vmname)
        exit(1)

    changed = False
    if options.do_list:
        do_list(vm)
    elif options.set_enable:
        vm.services[args[0]] = True
        changed = True
    elif options.set_disable:
        vm.services[args[0]] = False
        changed = True
    elif options.set_default:
        if vm.services.has_key(args[0]):
            vm.services.pop(args[0])
            changed = True

    if changed:
        qvm_collection.save()

    if not options.do_list:
        qvm_collection.unlock_db()


main()