#! /usr/bin/env python3
###############################################################################
version = "20:544101e2c265"
date = "2021-12-20"
###############################################################################
from sys import argv, exit
from pexpect import run, spawnu
from optparse import OptionParser
###############################################################################
b = "s3://customer-uploads-suse-com/"    # bucket base
l = "saml2aws login --disable-keychain"  # command to get a login token (okta)
###############################################################################
# ftp uploads are under ftpcs/ inside the bucket
# scc uploads are under the case number directory inside the bucket
###############################################################################
usage = """ftpget [options] substring
  -h for help

By default, list files containing the given substring.

For files uploaded from SCC, the option

-s <service request number> 

is needed and the option

-n <substring>

is optional.

For files uploaded via FTP the option

-f <substring>

is needed.

The additional option -g will download all files thus found.

Note: saml2aws must be in your path for the AWS login to work, and you need
a suitable ~/.saml2aws

The latest version of this should be available at:

http://code.rogerwhittaker.org.uk/ftpget/"""
###############################################################################
examples = """
Examples:

ftpget.py -s 00324003

list any files uploaded from SCC for case 00324003


ftpget.py -s 00324003 -n screenshot

list any files uploaded from SCC for case 00324003 including the substring
"screenshot" in their name


ftpget.py -s 00324003 -n screenshot -g

get the files listed by the previous example (filenames with spaces work)


ftpget.py -f sinincosplb9

list any files uploaded by ftp containing the substring "sinincosplb9" in
their names


ftpget.py -f sinincosplb9 -g

download the files listed by the previous example"""
###############################################################################
if len(argv) == 1:
    print(usage)
    exit()
###############################################################################
p = OptionParser(usage=usage)
p.add_option("-s",
             "--scc",
             dest="scc",
             help="case number of file uploaded via SCC")
###############################################################################
p.add_option("-n",
             "--name",
             dest="name",
             help="substring of name of SCC file")
###############################################################################
p.add_option("-f",
             "--ftp",
             dest="ftp",
             help="substring of ftp file")
###############################################################################
p.add_option("-g",
             "--get",
             dest="get",
             action="store_true",
             help="get files")
###############################################################################
p.add_option("-e",
             "--examples",
             dest="examples",
             action="store_true",
             help="show examples and exit")

p.add_option("-v",
             "--version",
             dest="version",
             action="store_true",
             help="show version and date, then exit")
###############################################################################
(o, x) = p.parse_args()
if o.examples:
    print(examples)
    exit()
if o.version:
    print("version: " + version)
    print("date:    " + date)
    exit()
###############################################################################
# first we test whether we need to log in, and log in if necessary
###############################################################################
t = run("aws --profile scc s3 ls" + " " + b + "ftpcs/", withexitstatus=True)
r = t[1]
if r != 0:
    child = spawnu(l)
    child.interact()
###############################################################################
def filename(line):
    """this is to deal with filenames that contain spaces - seems to work"""
    return line.split(line.split()[2] + " ")[1]
###############################################################################
searchterm = ""
###############################################################################
listftp = "aws --profile scc s3 ls" + " " + b + "ftpcs/"
###############################################################################
def copyftp(i):
    out = "aws --profile scc s3 cp"
    out = out + " " + '"' + b
    out = out + "ftpcs/" + i + '"' + " " + "."
    return out
###############################################################################
def listscc(sr):
    return "aws --profile scc s3 ls" + " " + b + sr + "/"
###############################################################################
def copyscc(sr, item):
    out = "aws --profile scc s3 cp"
    out = out + " " + '"' + b
    out = out + sr + "/" + item + '"' + " " + "."
    return out
###############################################################################
if o.ftp:
    items = []
    searchterm = o.ftp.strip()
    a = run(listftp)
    lines = a.decode().split("\n")
    for line in lines:
        if line.strip():
            if searchterm in line:
                print(line)
                print(filename(line))
                items.append(filename(line).strip())
    if o.get:
        for item in items:
            c = copyftp(item)
            print(str(c))
            run(c)
###############################################################################
if o.scc:
    items = []
    d = o.scc.strip()
    if o.name:
        searchterm = o.name.strip()
    a = run(listscc(d))
    lines = a.decode().split("\n")
    for line in lines:
        if line.strip():
            if searchterm in line:
                print(line)
                print(filename(line))
                items.append(filename(line).strip())
    if o.get:
        for item in items:
            c = copyscc(d, item)
            print(c)
            run(c)
###############################################################################
