#!/usr/bin/python3

import sys
import os
import pika
import logging
from battilo.timefmt import timestamp_fmt as ts

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


class MyHandler(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)
            try:
                os.mkdir(path + '/' + unit_name.upper())
                logging.info("PID {:>5} >> path {} created.".format(os.getpid(), unit_name.upper()))
            except FileExistsError:
                logging.info("PID {:>5} >> path {} already exists.".format(os.getpid(), unit_name.upper()))
            os.rename(file, path + '/' + unit_name.upper() + '/' + filename + '_' + str(ts.timestamp("tms") + file_extension))

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

def main():
    try:
        authorizer = UnixAuthorizer(
            rejected_users=["root"], require_valid_shell=True)
        handler = MyHandler
        handler.authorizer = authorizer
        handler.abstracted_fs = UnixFilesystem

        logging.basicConfig(format='%(asctime)s %(message)s',
                            filename='/var/log/ftpCsvRecv.log', level=logging.INFO)

        server = FTPServer(('', 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()