import getpass
import os
import socket
import sys
import traceback

import paramiko
from paramiko.py3compat import input

# setup logging
paramiko.util.log_to_file('demo_sftp.log')

# Paramiko client configuration
UseGSSAPI = False             # enable GSS-API / SSPI authentication
DoGSSAPIKeyExchange = True
Port = 22

# get hostname
username = ''
if len(sys.argv) > 1:
    hostname = sys.argv[1]
    if hostname.find('@') >= 0:
        username, hostname = hostname.split('@')
else:
    hostname = input('Hostname: ')
if len(hostname) == 0:
    print('*** Hostname required.')
    sys.exit(1)

if hostname.find(':') >= 0:
    hostname, portstr = hostname.split(':')
    Port = int(portstr)

# get username
if username == '':
    default_username = getpass.getuser()
    username = input('Username [%s]: ' % default_username)
    if len(username) == 0:
        username = default_username
if not UseGSSAPI:
    password = sys.argv[2]
else:
    password = None

# get host key, if we know one
hostkeytype = None
hostkey = None
try:
    host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
except IOError:
    try:
        # try ~/ssh/ too, because windows can't have a folder named ~/.ssh/
        host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
    except IOError:
        print('*** Unable to open host keys file')
        host_keys = {}

# if hostname in host_keys:
#     hostkeytype = host_keys[hostname].keys()[0]
#     hostkey = host_keys[hostname][hostkeytype]
#     print('Using host key of type %s' % hostkeytype)

# now, connect and use paramiko Transport to negotiate SSH2 across the connection
t = None
try:
    t = paramiko.Transport((hostname, Port))
    t.connect(hostkey, username, password, gss_host=socket.getfqdn(hostname),
              gss_auth=UseGSSAPI)
    sftp = paramiko.SFTPClient.from_transport(t)

    # clear folder:
    remoteArtifactPath = '/var/www/djangoApp/static/firebase/'
    filesInRemoteArtifacts = sftp.listdir(path=remoteArtifactPath)
    for file in filesInRemoteArtifacts:
        if file != 'node_modules':
            sftp.remove(remoteArtifactPath + file)

    # deploy new build
    filesInBuild = os.listdir(os.getcwd() + '/build/')
    for filename in filesInBuild:
        if filename != '.DS_Store' and not os.path.isdir('./build/{}'.format(filename)):
            sftp.put('./build/{}'.format(filename), '/var/www/djangoApp/static/firebase/{}'.format(filename))

    t.close()

except Exception as e:
    print('*** Caught exception: %s: %s' % (e.__class__, e))
    traceback.print_exc()
    try:
        t.close()
    except:
        pass
    sys.exit(1)
