#!/usr/bin/python3

import sys
import os
import pika
import logging
import argparse
from asebat.timefmt import timestamp_fmt as ts

from pprint import pprint

from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.authorizers import UnixAuthorizer
from pyftpdlib.filesystems import UnixFilesystem


class ASEHandler(FTPHandler):
    def on_file_received(self, file):
        with open(file, "r") as file_csv:
            for i, line in enumerate(file_csv.readlines(4096), 1):
                if i == 2:
                    unit_type, unit_name = line.strip('\n').replace(";","").replace(",","").split(" ")
                    logging.info("PID {:>5} >> {} {}".format(os.getpid(), unit_type.upper(), unit_name.upper()))
                    break
            file_csv.close
            path, filename_ext = os.path.split(file)
            filename, file_extension = os.path.splitext(filename_ext)
            new_path = '/home/' + self.username + '/received/' + unit_name.upper() + '/'
            new_filename = new_path + filename + '_' + str(ts.timestamp("tms") + file_extension)
            try:
                os.makedirs(new_path)
                logging.info("PID {:>5} >> path {} created.".format(os.getpid(), new_path))
            except FileExistsError:
                logging.info("PID {:>5} >> path {} already exists.".format(os.getpid(), new_path))
            try: 
                os.rename(file, new_filename)
                logging.info("PID {:>5} >> {} moved into {}.".format(os.getpid(), filename_ext, new_filename))
            except OSError:
                logging.error("PID {:>5} >> Error to move {} into {}.".format(os.getpid(), filename_ext, new_filename))

    def on_incomplete_file_received(self, file):
        # remove partially uploaded files
        os.remove(file)

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("-l", "--logfilename", help="log file", required=True)
    parser.add_argument("-p", "--port", help="passive port range start", type=int, required=True)
    parser.add_argument("-x", "--proxy", help="proxy address", required=True)
    args = parser.parse_args()

    try:
        authorizer = UnixAuthorizer(
            rejected_users=["root"], require_valid_shell=True)
        handler = ASEHandler
        handler.authorizer = authorizer
        handler.abstracted_fs = UnixFilesystem
        handler.masquerade_address = args.proxy
        _range = list(range(args.port, args.port + 20))
        handler.passive_ports = _range

        logging.basicConfig(format='%(asctime)s %(message)s',
                            filename="/var/log/" + args.logfilename, level=logging.INFO)

        server = FTPServer(('0.0.0.0', 21), handler)
        
        server.serve_forever()
    except KeyboardInterrupt:
        logging.info("PID {:>5} >> Error: {}.".format(os.getpid(), "Shutdown requested...exiting"))
    except Exception:
        print("{} - PID {:>5} >> Error: {}.".format(ts.timestamp("log"), os.getpid(), sys.exc_info()[1]))
        
if __name__ == "__main__":
        main()