# 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 argparse
import fnmatch
import sys
import time

import SoftLayer

parser = argparse.ArgumentParser(description='Reload and wait for SL hosts')

parser.add_argument('-y', '--yes',
                    action='store_true',
                    help="Don't prompt. Assume yes")

parser.add_argument('hosts',
                    metavar='HOST',
                    nargs='+',
                    help='host names to reload')

opts = parser.parse_args()

hosts = opts.hosts

client = SoftLayer.create_client_from_env()

vs = SoftLayer.VSManager(client)
ssh = SoftLayer.SshKeyManager(client)

instances = []

for i in vs.list_instances():
    for pattern in hosts:
        if fnmatch.fnmatchcase(i['fullyQualifiedDomainName'], pattern):
            instances.append(i)
            break

if not opts.yes:
    names = "\n".join(" - %s" % i['fullyQualifiedDomainName']
                      for i in instances)
    prompt = raw_input("Going to reload:\n%s\nStart [y/N]: " % names)

    if prompt.lower() not in ('y', 'yes'):
        sys.exit(0)

transactions = []

for instance in instances:
    try:
        transactions.append((instance['fullyQualifiedDomainName'],
                             instance['activeTransaction']))
    except KeyError:
        pass

if transactions:
    msgs = ["%s: %s" % (n, t['transactionStatus']['name'])
            for n, t in transactions]
    print("Aborting due to active transactions in target list:\n%s" %
          "\n".join(msgs))
    sys.exit(1)

# install all the ssh keys we can find
ssh_keys = [key['id'] for key in ssh.list_keys()]

for instance in instances:
    fqdn = instance['fullyQualifiedDomainName']
    try:
        vs.reload_instance(instance['id'], ssh_keys=ssh_keys)
    except SoftLayer.exceptions.SoftLayerAPIError as e:
        print("Failed to reload %s due to %s" % (fqdn, e))
    else:
        print("Reloaded %s" % fqdn)

# wait for them to reload
while True:
    instances = [i.get('activeTransaction') for i in vs.list_instances()
                 if i['fullyQualifiedDomainName'] in hosts]

    if not any(instances):
        break

    sys.stdout.write(".")
    sys.stdout.flush()
    time.sleep(5)

sys.stdout.write("\n")

@@ -1129,16 +1129,61 @@
 (client)
+%0Ahardware = SoftLayer.HardwareManager(client)
 %0A%0Ainstan
@@ -1220,16 +1220,43 @@
 tances()
+ + hardware.list_hardware()
 :%0A    fo
@@ -1427,26 +1427,17 @@
 names = 
-%22%5Cn%22.join(
+%5B
 %22 - %25s%22 
@@ -1471,49 +1471,64 @@
 me'%5D
-%0A                      for i in instances
+ for i in instances%5D%0A    names = %22%5Cn%22.join(sorted(names)
 )%0A  
@@ -2272,32 +2272,158 @@
 Name'%5D%0A    try:%0A
+        if instance.get('hardwareStatusId'):%0A            hardware.reload(instance%5B'id'%5D, ssh_keys=ssh_keys)%0A        else:%0A    
         vs.reloa
@@ -2660,33 +2660,166 @@
 oad%0A
-while True:%0A    instances
+instance_names = %5Bi%5B'fullyQualifiedDomainName'%5D for i in instances%5D%0A%0Awhile True:%0A    all_waiting = vs.list_instances() + hardware.list_hardware()%0A%0A    waiting
  = %5B
@@ -2858,30 +2858,20 @@
  in 
-vs.list_instances()%0A  
+all_waiting%0A
     
@@ -2917,20 +2917,29 @@
 me'%5D in 
-host
+instance_name
 s%5D%0A%0A    
@@ -2949,25 +2949,23 @@
 not any(
-instances
+waiting
 ):%0A     

Support baremetal nodes in reload