#!/usr/bin/env python
#
# Created as part of the StratusLab project (http://stratuslab.eu),
# co-funded by the European Commission under the Grant Agreement
# INFSO-RI-261552."
#
# Copyright (c) 2010, SixSq Sarl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys
from time import sleep

import os
import subprocess
from optparse import OptionParser

# initialize console logging
import stratuslab.api.LogUtil as LogUtil

LogUtil.get_console_logger()


class RemoteShutdown(object):
    """A command line to remotely shutdown a machine"""

    def __init__(self):
        usage = '%prog [options]'

        parser = OptionParser(usage=usage)

        parser.description = '''
Utility to do a remote shutdown of the machine identified by the
options.
'''

        parser.add_option('-p', '--port', dest='sshPort', type='int',
                          help='ssh port to connect on', default=22, metavar='PORT')
        parser.add_option('-t', '--timeout', dest='timeout', type='int',
                          help='time to wait for complete shutdown', default=30)
        parser.add_option('-m', '--hostname', dest='hostname',
                          help='hostname of the machine to shutdown', default='localhost')
        parser.add_option('-k', '--key', dest='sshKey',
                          help='ssh key to connect to the frontend',
                          metavar='KEY_PATH',
                          default=os.path.expandvars("$HOME/.ssh/stratuslab-stock.key"))

        self.options, self.args = parser.parse_args()

        self.doWork()

    def doWork(self):
        print 'Shutting down %s...' % self.options.hostname
        shutdownCmd = ['ssh', '-l', 'root', '-i', self.options.sshKey,
                       '-p', str(self.options.sshPort), self.options.hostname,
                       'shutdown -h now']
        process = subprocess.Popen(shutdownCmd)
        process.wait()

        if process.returncode != 0:
            print 'An error occurred while shutting down system'
            sys.exit(1)

        sleep(self.options.timeout)
        print 'System halted successfully'


if __name__ == '__main__':
    try:
        RemoteShutdown()
    except KeyboardInterrupt:
        print '\n\nExecution interrupted by the user... goodbye!'
