#!/usr/bin/env python
# Copyright (C) 2012-2013  Peter Hatina <phatina@redhat.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, see <http://www.gnu.org/licenses/>.

import sys

from lmi.lmi_options import LmiBasicOptions
from lmi.lmi_address import LmiIpv4Addr, LmiHostGenerator
from lmi.lmi_client_power import LmiPowerClient

class LmiPowerOptions(LmiBasicOptions):
    def __init__(self):
        super(self.__class__, self).__init__(
            "Available actions:\n"
            "  poweroff, reboot, suspend, hibernate\n"
            "  force-poweroff, force-reboot\n")
        self._parser.set_usage("Usage %prog [options] action")

    @property
    def good(self):
        return len(self._pos_options) == 1

    @property
    def action(self):
        return self._pos_options[0] if self.good and self._pos_options[0] else ""

if __name__ == "__main__":
    options = LmiPowerOptions()
    options.parse(sys.argv)
    if not options.good:
        options.print_wrong_usage()
        sys.exit(1)

    client_failed = False
    client_hostnames = LmiHostGenerator.enumerate(options.hostname)
    client_action = options.action.lower()
    for client_hostname in client_hostnames:
        if not client_hostname:
            continue
        client = LmiPowerClient(client_hostname.name, options.username, options.password)
        actions = {
            "reboot": (client.reboot, "Reboot: "),
            "poweroff": (client.poweroff, "Poweroff: "),
            "suspend": (client.suspend, "Suspend: "),
            "hibernate": (client.hibernate, "Hibernate: ")
        }

        if not client_action in actions:
            sys.stdout.write("No such action to perform!\n")
            sys.exit(1)

        (rval, _, errorstr) = actions[client_action][0]()
        if rval:
            sys.stdout.write("%s: %s\n" % (client_hostname.name,
                actions[client_action][1] + errorstr if errorstr else "ok"))
        else:
            sys.stderr.write("%s: %s\n" % (client_hostname.name, errorstr))
            client_failed = True

    sys.exit(client_failed)
