#!/usr/bin/python2
# -*- encoding: utf8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2014  Marek Marczykowski-Górecki <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 optparse import OptionParser
import optparse

import os
import sys
from qubes.qubes import QubesVmCollection
from qubes.qubesutils import updates_vms_toggle,updates_dom0_toggle,\
    updates_dom0_status,updates_vms_status
from qubes.qubes import vmm


def main():

    usage = "%prog enable|disable|status\n"\
            "  Enable or disable globally checking for updates (both dom0 and VM)"
    parser = OptionParser (usage)
    parser.add_option("--offline-mode", dest="offline_mode",
                      action="store_true", default=False,
                      help=optparse.SUPPRESS_HELP)

    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.error("You must provide an action")

    action = args[0]
    if action not in ['enable', 'disable', 'status']:
        parser.error("Invalid action")

    if options.offline_mode:
        vmm.offline_mode = True

    qvm_collection = QubesVmCollection()
    if action == 'status':
        qvm_collection.lock_db_for_reading()
    else:
        qvm_collection.lock_db_for_writing()
    qvm_collection.load()
    if action == 'enable':
        updates_dom0_toggle(qvm_collection, True)
        updates_vms_toggle(qvm_collection, True)
    elif action == 'disable':
        updates_dom0_toggle(qvm_collection, False)
        updates_vms_toggle(qvm_collection, False)
    else:
        if updates_dom0_status(qvm_collection):
            print "dom0: enabled"
        else:
            print "dom0: disabled"
        status_vms = updates_vms_status(qvm_collection)
        if status_vms is None:
            print "vms: mixed"
        elif status_vms:
            print "vms: enabled"
        else:
            print "vms: disabled"

    if action != 'status':
        qvm_collection.save()
    qvm_collection.unlock_db()

if __name__ == "__main__":
    main()