"""
  ____ _____ ____ 
 |  _ \_   _/ ___|
 | |_) || || |    
 |  _ < | || |___ 
 |_| \_\|_| \____|

Script to set the RTC using the browser time (script used by the web UI).

/usr/bin/python3 /var/www/nebuleair_pro_4g/RTC/set_with_browserTime.py '2024-01-30 12:48:39'

"""

import sys
from datetime import datetime
import smbus2

# DS3231 I2C address
DS3231_ADDR = 0x68
REG_TIME = 0x00

def dec_to_bcd(dec):
    """Convert decimal to BCD."""
    return (dec // 10 * 16) + (dec % 10)

def set_rtc(bus, year, month, day, hour, minute, second):
    """Set the RTC time."""
    second_bcd = dec_to_bcd(second)
    minute_bcd = dec_to_bcd(minute)
    hour_bcd = dec_to_bcd(hour)
    day_bcd = dec_to_bcd(day)
    month_bcd = dec_to_bcd(month)
    year_bcd = dec_to_bcd(year - 2000)  # RTC stores years since 2000

    bus.write_i2c_block_data(DS3231_ADDR, REG_TIME, [
        second_bcd, minute_bcd, hour_bcd, 0x01, day_bcd, month_bcd, year_bcd
    ])

def main():
    if len(sys.argv) != 2:
        print("Usage: python3 set_rtc.py 'YYYY-MM-DD HH:MM:SS'")
        sys.exit(1)

    rtc_time_str = sys.argv[1]
    rtc_time = datetime.strptime(rtc_time_str, '%Y-%m-%d %H:%M:%S')

    bus = smbus2.SMBus(1)
    set_rtc(bus, rtc_time.year, rtc_time.month, rtc_time.day,
            rtc_time.hour, rtc_time.minute, rtc_time.second)
    print(f"RTC updated to: {rtc_time}")

if __name__ == "__main__":
    main()
