#!/opt/dosis2/bin/python3-venv

import sys
import getopt
import subprocess
import scp
import paramiko
import psycopg2
import getpass


def get_teammates():
    try:
        conn = psycopg2.connect("dbname='dosis2' user='dsuper' host='localhost'")
        cur = conn.cursor()
        cur.execute("""SELECT tag, site_ip FROM equipment.dafe""")
        rows = cur.fetchall()
        clean_rows = [row for row in rows if row[0] != 'UNKNOWN' and row[0] !='SYSTEM']
        return clean_rows
    except psycopg2.OperationalError as err:
        print(err)


def one_ping_only(host, tag):
    try:
        cmd = ['fping', host]
        rv = subprocess.call(cmd)
        if rv < 0 or rv > 0:
            print(('Host found: ', host))
            return False
        else:
            print(('Host not found: ', host))
            return True
    except subprocess.CalledProcessError as called_proc_err:
        print(('CalledProcErr: ', err))


def send_file(tag, host, user, frm, put):
    try:
        print(('Sending file as {user} to {tag} at /home/{user}, input password'.format(user=user, tag=tag)))
        password = getpass.getpass()
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(
            hostname = hostname,
            username = username,
            password = password
        )
        with scp.SCPClient(ssh_client.get_transport()) as scp_put:
            scp_put.put(frm, remote_path=put, recursive=False, preserve_times=False)
            return True
    except paramiko.AuthenticationException as auth_err:
        print(('Authentication ERROR: ', auth_err))
    except paramiko.SSHException as ssh_err:
        print(('SSH ERROR: ', ssh_err))
    except Exception as err:
        print(('Unknown Err: ', err))
    finally:
        ssh_client.close()


def run(argv):
    try:
        send_file = ''
        opts, args = getopt.getopt(argv, 'hf:', ['file='])
        for opt, arg in opts:
            if opt == '-h':
                print('scp-to-team -f <sendfile>')
                sys.exit()
            elif opt in ('-f', '--file'):
                send_file = arg
    except getopt.GetoptError:
        print('ERR: incorrect usage scp-to-team -f <sendfile>')
        sys.exit(2)


    try:
        tm = get_teammates()
        for t in tm:
            if one_ping_only(t[0], t[1]):
                send_file(t[0], t[1], 'dSupport', send_file, '/home/dSupport')
    except Exception as err:
        print(err)


if __name__ == '__main__':
    run(sys.argv[1:])
