#!/usr/bin/env python3
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Inches, Pt
from datetime import date
import time
import os
import mysql.connector
import sys
import subprocess

db_config = {
    "host": "localhost",
    "user": "rsghihjbaoh",
    "password": "dD8X/p99JY1w",
    "database": "asexpresstms"
}

def convert_docx_to_pdf(input_docx, output_pdf, parentDir):
    try:
        env_vars = {'HOME': '/var/www/html/tms/public/driversdocs/temp'}
        subprocess.run(['libreoffice', '--headless', '--convert-to', 'pdf', input_docx, '--outdir', parentDir], env=env_vars)
        os.rename(parentDir+'/tempsingle.pdf', output_pdf)
    except Exception as e:
        sys.exit()

def lease_pdf(carrier,driver,parentDir,user_id):
    today = date.today()
    datetoday = today.strftime("%m/%d/%Y")
    doc = Document()
    doc.styles['Normal'].font.name = "Arial MT"
    doc.styles['Normal'].font.size = Pt(11)
    para = doc.add_paragraph()
    text1 = para.add_run('LEASE AGREEMENT.')
    text1.bold = True
    text1.font.name = 'Arial'
    text1.font.size = Pt(18)
    para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    para = doc.add_paragraph()
    text2 = para.add_run('Note꞉ This Lease Agreement should be maintained in the Equipment during the term of the Agreement.')
    text2.bold = True
    text2.font.name = 'Arial'
    text2.font.size = Pt(7.5)
    para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    para = doc.add_paragraph('        I.    I, ' + carrier['companyname'] + ' (Carrier/Registrant) Address꞉ ' + carrier['address'] + ' and ')
    run = para.add_run('_____'+str(driver[5])+'___')
    run.underline = True
    run = para.add_run('. (Equipment Owner) are parties to a written Lease Agreement (Agreement), whereby the Equipment Owner has leased to the Carrier certain motor vehicle equipment listed below, owned and controlled by the Equipment Owner, whereby the Equipment Owner is providing the Carrier as operator or operators of the Equipment for the purpose of loading, transporting and unloading freight.\n')
    para = doc.add_paragraph('        II.    The Original Agreement is on ﬁle at the Carrier’s General Ofﬁce. A copy of this Lease Agreement and receipt for the Equipment must be carried on the Equipment as required by 49 CFR §376. Carrier veriﬁes that the Equipment is being operated by the Carrier, pursuant to the terms of the Agreement.\n')
    para = doc.add_paragraph('        III.    Equipment Owner/Equipment Information.')
    para = doc.add_paragraph('Name:')
    run = para.add_run('___'+str(driver[5])+'______')
    run.underline = True
    para = doc.add_paragraph('dba:_________________________________________')
    para = doc.add_paragraph('Address:')
    run = para.add_run('__'+str(driver[6])+'______')
    run.underline = True

    para = doc.add_paragraph('Year:')
    run = para.add_run('__'+str(driver[3])+'__')
    run.underline = True

    run = para.add_run('Make:')
    run = para.add_run('__'+str(driver[2])+'__')
    run.underline = True

    run = para.add_run('VIN:__')
    run = para.add_run(str(driver[4])+'__\n')
    run.underline = True

    para = doc.add_paragraph(
        '        IV.    Duration of Lease Agreement and Termination. The Lease Agreement shall begin on the date below and shall remain in effect until terminated by either party, giv‑ ing notice to that effect. Notice may be given personally, by mail or by fax at the address or fax number shown in the Lease Agreement.\n')
    table = doc.add_table(rows=1, cols=2)
    para = table.rows[0].cells[0].paragraphs[0]
    run = para.add_run("MOTOR CARRIER/REGISTER").bold=True
    run = para.add_run("\nBy:")
    run = para.add_run().add_picture(str(parentDir)+'/public/driversdocs/temp/carrier_sign.png')
    run = para.add_run("\n"+carrier['companyname']+" (manager)\nDate: " + carrier['date'] + '\nMC #꞉ '+ str(carrier['mc']) +'\nUSDOT #꞉ ' + str(carrier['usdot']))
    para = table.rows[0].cells[1].paragraphs[0]
    para.add_run("EQUIPMENT OWNER").bold=True
    para.add_run("\n\nBy:________________\n\nDate:")
    run = para.add_run('__'+datetoday+'__')
    run.underline = True
    para = doc.add_paragraph()
    text3 = para.add_run('Printed by authority of the State of Illinois. November 2011 — 21 — VSD 683.225.')
    text3.bold = True
    text3.font.size = Pt(6)
    para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    if os.path.isdir(parentDir+"/public/driversdocs/"+str(user_id)) == False:
        os.mkdir(parentDir+'/public/driversdocs/'+str(user_id))
    time.sleep(1)
    doc.save(parentDir+'/public/driversdocs/'+str(user_id)+'/tempsingle.docx')
    os.chmod(parentDir+'/public/driversdocs/'+str(user_id)+'/tempsingle.docx', 0o755)
    time.sleep(1)
    convert_docx_to_pdf(parentDir+"/public/driversdocs/"+str(user_id)+"/tempsingle.docx", parentDir+"/public/driversdocs/"+str(user_id)+"/Lease_"+str(driver[0])+".pdf", parentDir+"/public/driversdocs/"+str(user_id))
    time.sleep(1)
    os.remove(parentDir+"/public/driversdocs/"+str(user_id)+"/tempsingle.docx")
    time.sleep(1)

def policy(driver,truck,company,parentDir):
    today = date.today()
    datetoday = today.strftime("%m/%d/%Y")
    doc = Document()
    doc.styles['Normal'].font.name = "Arial MT"
    doc.styles['Normal'].font.size = Pt(10)
    para = doc.add_paragraph()
    text1 = para.add_run('INDEPENDENT DRIVER AND POLICY AGREEMENT')
    text1.bold = True
    text1.font.name = 'Arial'
    text1.font.size = Pt(12)
    para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    para = doc.add_paragraph('I ')
    run = para.add_run('  ' + str(driver['firstname']) + ' ' + str(driver['lastname']) + '  ')
    run.underline = True
    run = para.add_run(' understand and agree to the terms in this contract, dated ')
    run = para.add_run('  ' + datetoday + '  ')
    run.underline = True

    para = doc.add_paragraph('1. I understand that I am an Independent Contract Driver. This Agreement shall remain in full force and effective for a 6 months period beginning on the date first written above and continuing thereafter on a year-to-year basis.\n')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('2. I understand that additions and deletions can be made at any time to this contract policy agreement by ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) and I will be provided with a new copy to review and understand in a timely manner before signing.')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('3. I understand that I am responsible for filing my own taxes with the Internal Revenue Service and Resident State Revenue Department.')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) will provide me with a 1099Form.')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('4. I understand that my rate of pay will be based on a percent of the Net Load Pay. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('5. I understand that ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) does not guarantee, nor am I obligated to haul a specific number of loads or earn a specific amount of revenue. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('6. I understand I will be provided copies of all invoices to verify amounts of pay for Net Load Pay. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('7. I accept the rate of 40% of the Net Load Pay All exclude diesel and tolls), all cash needs to be returned to the company. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('8. I agree to follow and uphold all regulations set by the Department of Transportation and Federal Motor Carrier Safety Administration. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('9. I understand that ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) has a zero-tolerance policy and does not permit anything there is deemed contraband or illegal by the laws of the United States of America and accept full responsibility and penalties due to my own actions regarding this policy. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('10. I understand taking the tractor (pick-up truck) and trailer anywhere other than authorized trip origin route and destination or my personal place of residence requires written authorization. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('11. I understand that the truck must be serviced every 10,000 miles and receipts will be required. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('12. I understand that ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) at any time can request a random viewing of the truck and trailer. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('13. I understand that the truck and trailer assigned to me must be returned in a timely matter and in clean operating condition at the request of ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) for any reason. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('14. I understand if I do not return the truck and trailer assigned to me with ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) upon their request this is considered abandonment or stealing of private property and I will be liable for any and all recovery expenses that ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) incurs getting the truck returned to them. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('15. I understand that due to my abandoning truck and trailer I have the right to use the trucking phrase "abandonment" as my defense if the units are stolen as a result of abandonment I understand that it is my responsibility to return the assigned truck and trailer to ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) and that criminal charges can and will be brought against me for commercial vehicle theft if I fail to do so. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('16. It is my responsibility to make and keep copies of the Vehicle Trip Report, Vehicle Expense Report, Bill (s) of Lading and all receipts of each trip until ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) has been paid by the broker or shipper and I have been paid by ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company). If the original copies are lost in the mail or due to my negligence and I cannot provide copies I will be responsible for all expenses and lost earnings to ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) as well as my loss of pay for the said load. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('17. I understand it is not the responsibility of ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) to reimburse me for personal expenses. I will not be compensated for personal expenses incurred during job hauls such as and not limited to: meals, cellular phone usage, lodging, motor vehicle violation tickets (of all kinds) due to negligence plus those described but not limited to those detailed in term number of this agreement. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('18. I understand that ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) does not guarantee, nor am I obligated to haul a specific number of loads, or earn a specific amount of revenue, or work a specific number of hours, or work specific days of the week. Any revenue I generate or pay I receive from ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) will be solely for individual job hauls I accept to complete and have completed. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('19. I understand that ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) does not guarantee a specific or average amount of revenue/pay. I retain full control and discretion on any hauling jobs I choose to accept, I retain full control and discretion on the amount of, hours I choose to work, I retain full control and discretion on the hours and days I choose to work; thus I retain full discretion on the potential revenue I may or may not generate based on the hauling jobs I accept or do not accept to complete. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('20. I understand that ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) does not guarantee a profit. I understand that I may even incur losses due to unforeseeable complications with the hauling job or due to damages or penalties caused to the motor vehicle or trailer to ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) as a result of my negligence or failure to adhere to DOT/FMCSA regulatory requirements. ')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contractor Initials')

    para = doc.add_paragraph('21.  I agree to uphold all regulations set by the Department of Transportation and Federal Motor Carrier Safety Administration.')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contrator Initials')

    para = doc.add_paragraph('22. I understand, acknowledge and give ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    para.add_run('(Company) and its representatives permission to withdraw and/ or deduct monies from my net revenue/ pay for the following conditions:')
    para = doc.add_paragraph('     • Deposit amount of 2,500 USD, on hold as a guarantee in case of company policy violations. After 45 days, if no accident or any other damage happened , if minimum employment term is met and two week notice is given the deposit of $2,500.00 (two thousand five hundred dollars) will be paid out infull via check or added to the last payout amount.\n     • Payment of tolls and road taxes, and any fees assigned\n     • Weight/Scale violation fees\n     • Parking\n     • Traffic violations\n     • Shortages I trip funds by my failure to provide receipts for maintenance, fuel, supplies, or other items and services that I have advanced monies to purchase on behalf of ')
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    run = para.add_run('(Company) or its representatives.\n     • My failure to provide COD(cash on delivery, check on delivery), COP(cash on pick-up, check on pick-up).\n     •Damaged cargo due to my negligence. I must document all bills of lading if I was not present or allowed to watch the loading or unloading of freight.\n     • Any physical damage to the tractor (pick-up truck) or trailer assigned to me if I am found at fault in an accident or incident due to my negligence.\n     • Any towing charges for vehicles assigned to me if I am found at fault in an accident or due to my negligence.\n     • Fees and penalties assessed by the US DOT/FMCSA due to driver qualification violations.\n     • Toll and fuel costs for undisclosed routes of travel or undisclosed use of vehicles.')
    run = para.add_run('  ' + str(driver['firstname'][0]).upper() + str(driver['lastname'][0]).upper() + '  ')
    run.underline = True
    para.add_run('Contrator Initials')

    para = doc.add_paragraph()
    run = para.add_run('  ' + str(company) + '  ')
    run.underline = True
    run = para.add_run(' may terminate this Agreement at any time, in case of failure to fulfill the contract by the driver.')

    para = doc.add_paragraph('I ')
    run = para.add_run('  ' + str(driver['firstname']) +' '+ str(driver['lastname']) + '  ')
    run.underline = True
    run = para.add_run(' certify that I have read, understand and agree to the provision.\n')

    table = doc.add_table(rows=2, cols=2)
    para = table.rows[0].cells[0].paragraphs[0]
    run = para.add_run("________________________\nContract Driver Signature")
    para = table.rows[1].cells[0].paragraphs[0]
    run = para.add_run().add_picture(str(parentDir) + '/public/driversdocs/temp/carrier_sign.png')
    run = para.add_run("\n________________________\nCompany Representative")

    para = table.rows[0].cells[1].paragraphs[0]
    run = para.add_run('  ' + datetoday + '  \n')
    run.underline = True
    para.add_run("Date")
    para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    para = table.rows[1].cells[1].paragraphs[0]
    run = para.add_run('\n\n  ' + datetoday + '  \n')
    run.underline = True
    para.add_run("Date")
    para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT

    para = doc.add_paragraph()
    run = para.add_run('LICENSE INFORMATION ')
    run.bold = True
    run = para.add_run('(please attach copy)')
    para = doc.add_paragraph('Name on Driver\'s License: ')
    run = para.add_run('  ' + str(driver['firstname']) + ' ' + str(driver['lastname']) + ' \n')
    run.underline = True
    run = para.add_run('Driver\'s License Number: ')
    run = para.add_run('  ' + str(driver['dl']).upper() + ' \n')
    run.underline = True
    run = para.add_run('Expiration Date: ')
    run = para.add_run('  ' + str(driver['dlExpired']) + ' \n')
    run.underline = True
    run = para.add_run('State of issue: ')
    run = para.add_run('  ' + str(driver['dlState']) + ' ')
    run.underline = True

    para = doc.add_paragraph()
    run = para.add_run('TRUCK INFORMATION')
    run.bold = True
    para = doc.add_paragraph('Year: ')
    run = para.add_run('  ' + str(truck[3]) + '  ')
    run.underline = True
    run = para.add_run(' Make: ')
    run = para.add_run('  ' + str(truck[2]) + '  ')
    run.underline = True
    run = para.add_run(' VIN: ')
    run = para.add_run('  ' + str(truck[4]).upper() + '  ')
    run.underline = True

    if os.path.isdir(parentDir + "/public/driversdocs/" + str(driver['id'])) == False:
        os.mkdir(parentDir + '/public/driversdocs/' + str(driver['id']))
        print(parentDir + '/public/driversdocs/' + str(driver['id']))
    time.sleep(1)
    doc.save(parentDir + '/public/driversdocs/'+str(driver['id'])+'/tempsingle.docx')
    os.chmod(parentDir + '/public/driversdocs/'+str(driver['id'])+'/tempsingle.docx', 0o755)
    time.sleep(1)
    convert_docx_to_pdf(parentDir + "/public/driversdocs/"+str(driver['id'])+"/tempsingle.docx", parentDir + "/public/driversdocs/" + str(driver['id']) + "/Policy.pdf", parentDir + "/public/driversdocs/" + str(driver['id']))
    time.sleep(1)
    os.remove(parentDir + "/public/driversdocs/"+str(driver['id'])+"/tempsingle.docx")
    time.sleep(1)

def getTruckInformation(truck_id):
    cursor = connection.cursor()
    select_query = "SELECT truck_type, number, make, year, vin, lease_name, lease_address FROM trucks WHERE id = (%s)"
    cursor.execute(select_query, (truck_id,))
    trucks = cursor.fetchone()
    cursor.close()
    return trucks

def getCarrierInfo():
    cursor = connection.cursor()
    select_query = "SELECT iname, colvalue FROM settings WHERE type = 'fakecompany'"
    cursor.execute(select_query)
    companyRes = cursor.fetchall()
    if companyRes:
        company = {
            'companyname': companyRes[0][1],
            'address': companyRes[1][1],
            'date': companyRes[2][1],
            'mc': companyRes[3][1],
            'usdot': companyRes[4][1],
            }
        cursor.close()
        return company
    else:
        cursor.close()
        return None

def getDriverLicense(driver_id):
    cursor = connection.cursor()
    select_query = "SELECT users.id, users.firstname, users.lastname, drivers.dl_number, drivers.dl_state, drivers.dl_expired, drivers.truck_id, drivers.trailer_id FROM users LEFT JOIN drivers ON drivers.user_id = users.id WHERE users.id = %s"
    cursor.execute(select_query, (driver_id,))
    result = cursor.fetchone()
    if result is not None:
        driver = {
            'id': result[0],
            'firstname': result[1],
            'lastname': result[2],
            'dl': result[3],
            'dlState': result[4],
            'dlExpired': result[5].strftime("%m/%d/%Y") if result[5] else None,
            'truckId': result[6],
            'trailerId': result[7],
        }
        cursor.close
        return driver
    cursor.close
    return None

if len(sys.argv)>1:
    driverId = sys.argv[1]
    parentDir = '/var/www/html/tms'
    connection = mysql.connector.connect(**db_config)
    if os.path.isfile(parentDir + '/public/driversdocs/'+str(driverId)+'/tempsingle.docx'):
        os.remove(parentDir + '/public/driversdocs/'+str(driverId)+'/tempsingle.docx')

    carrier = getCarrierInfo()
    if not carrier['companyname'] and not carrier['address'] and not carrier['date'] and not carrier['mc'] and not carrier['usdot']:
        connection.close()
        print('error3', end='')
        sys.exit()

    if driverId:
        driver = getDriverLicense(driverId)
        if driver:
            if driver['dl'] and driver['dlState'] and driver['dlExpired']:
                if driver['truckId']:
                    truckInfo = getTruckInformation(driver['truckId'])
                    lease_pdf(carrier,truckInfo,parentDir,driverId)
                    policy(driver,truckInfo,carrier['companyname'],parentDir)
                else:
                    connection.close()
                    print('error1', end='')
                    sys.exit()

                if driver['trailerId']:
                    trailerInfo = getTruckInformation((driver['trailerId']))
                    lease_pdf(carrier,trailerInfo,parentDir,driverId)
                else:
                    connection.close()
                    print('error1', end='')
                    sys.exit()
            else:
                connection.close()
                print('DL/CDL not filled.', end='')
                sys.exit()
        else:
            connection.close()
            print('User is not a driver.',end='')
            sys.exit()
        connection.close()
        print('done', end='')
    else:
        connection.close()
        print('This user cannot be generated.', end='')
        sys.exit()
else:
    print('Script can be run only inner enviroment.',end='')
