'''
Script to add the SSL certificate
ex: 
python3 /var/www/nebuleair_pro_4g/SARA/SSL/sara_add_certif_v2.py ttyAMA2 2

'''
import serial
import time
import sys
import json
import os

parameter = sys.argv[1:]  # Exclude the script name
port = '/dev/' + parameter[0]  # e.g., ttyAMA2
timeout = float(parameter[1])  # e.g., 2 seconds

baudrate = 115200

def read_complete_response(serial_connection, timeout=2, end_of_response_timeout=2):
    response = bytearray()
    serial_connection.timeout = timeout
    end_time = time.time() + end_of_response_timeout

    while True:
        if serial_connection.in_waiting > 0:
            data = serial_connection.read(serial_connection.in_waiting)
            response.extend(data)
            end_time = time.time() + end_of_response_timeout  # Reset timeout on new data
        elif time.time() > end_time:
            break
        time.sleep(0.1)

    return response.decode('utf-8', errors='replace')

try:
    with open("/var/www/nebuleair_pro_4g/SARA/SSL/isrgrootx1.der", "rb") as cert_file:
        certificate = cert_file.read()

    size_of_string = len(certificate)

    ser = serial.Serial(port=port, baudrate=baudrate, timeout=timeout)
    command = f'AT+USECMNG=0,0,"myCertificate2",{size_of_string}\r'
    ser.write((command + '\r').encode('utf-8'))
    response_SARA_1 = read_complete_response(ser)
    print("Write certificate metadata")
    print(response_SARA_1)

    time.sleep(1)

    ser.write(certificate)
    response_SARA_2 = read_complete_response(ser)
    print("Write certificate data")
    print(response_SARA_2)

except serial.SerialException as e:
    print(f"Serial Error: {e}")
except FileNotFoundError as e:
    print(f"File Error: {e}")
except Exception as e:
    print(f"Unexpected Error: {e}")
finally:
    if 'ser' in locals() and ser.is_open:
        ser.close()
