#!/usr/bin/env python3
"""Check, update or downgrade the BMC firmware of a Time Tagger X.

The Time Tagger X has a board management controller (BMC) with its own firmware.
This script flashes one of the two BMC firmware files published together with it:

    ttx-bmc-firmware-2.6.bin   BMC firmware 2.6, shipped with new units from early 2027
    ttx-bmc-firmware-2.3.bin   BMC firmware 2.3, shipped with earlier units

Requirement: Time Tagger software 2.23.0 or newer, also for a downgrade to 2.3.

Usage:
    python update_ttx_bmc_firmware.py
    python update_ttx_bmc_firmware.py ttx-bmc-firmware-2.6.bin
    python update_ttx_bmc_firmware.py ttx-bmc-firmware-2.3.bin --serial <serial number>

Without a firmware file, the script only shows the current BMC firmware.

The new firmware becomes active only after the Time Tagger X was disconnected from mains power:
switch it to standby with the power button, unplug the power cable, wait a few seconds,
plug it back in and switch the device on. The power button alone is not enough.
"""

import argparse
import hashlib
import os
import sys

from Swabian import TimeTagger

# SHA-256 of the published firmware files: (version, build info) that the BMC reports after flashing
KNOWN_FIRMWARE = {
    '8494afbb6a54852894817bf70e48a8a61b435cd4093bd0d24e13430d48491ccc': ('2.3', 'v2.3-28-gf492d11'),
    '58eea798c1dd868f447f5c5729951ad2aaf7c1640a959d70bcd96ec0123be2db': ('2.6', 'v2.6'),
}
# Builds of the published firmware files; units with any other build are handled by support
PUBLISHED_BUILDS = {build for _, build in KNOWN_FIRMWARE.values()}
# First Time Tagger software version that can connect to a Time Tagger X with BMC firmware 2.6
MIN_SOFTWARE_VERSION = (2, 23)
# Oldest hardware revision (1.x) for which BMC firmware 2.6 is released
MIN_HARDWARE_REVISION_FOR_2_6 = 2
SUPPORT = 'support@swabianinstruments.com'


def check_software_version():
    version = TimeTagger.getVersion()
    major, minor = (int(part) for part in version.split('.')[:2])
    if (major, minor) < MIN_SOFTWARE_VERSION:
        sys.exit(f'This script requires Time Tagger software 2.23.0 or newer, but {version} is installed.\n'
                 'Older versions do not support BMC firmware 2.6.\n'
                 'Please install the latest version from https://www.swabianinstruments.com/time-tagger/downloads/')


def identify_firmware(path):
    """Return (version, build info) of a published firmware file, or exit for any other file."""
    if not os.path.isfile(path):
        sys.exit(f'Firmware file not found: {path}')
    with open(path, 'rb') as file:
        digest = hashlib.sha256(file.read()).hexdigest()
    if digest not in KNOWN_FIRMWARE:
        sys.exit(f'{path} is not one of the BMC firmware files published with this script.')
    return KNOWN_FIRMWARE[digest]


def select_serial(serial):
    if serial:
        return serial
    serials = TimeTagger.scanTimeTagger()
    if not serials:
        sys.exit('No Time Tagger found. Please connect the Time Tagger X and close all programs that use it.')
    if len(serials) > 1:
        sys.exit(f'Several Time Taggers found: {", ".join(serials)}. Please select one with --serial.')
    return serials[0]


def check_device(tagger):
    """Exit unless the device is a Time Tagger X whose BMC firmware can be changed."""
    if tagger.getModel() != 'Time Tagger X':
        sys.exit(f'This device is a {tagger.getModel()}. This script is for the Time Tagger X only.')
    # getPcbVersion() returns for example '1.4 (2)'; the first part is the hardware revision
    if tagger.getPcbVersion().split()[0] == '1.0':
        sys.exit('This Time Tagger X has hardware revision 1.0 and an older BMC firmware, which cannot be updated.')


def read_bmc_status(tagger):
    """Return (version, build info, firmware slot, hardware revision) of the BMC."""
    bmc = tagger.getSensorData()[0]['bmc']
    if not bmc.get('readout successful') or 'version' not in bmc:
        # Older BMC firmware versions cannot be read, and therefore not updated, by the Time Tagger software
        sys.exit('The BMC of this Time Tagger X cannot be read by the Time Tagger software, so this script cannot '
                 f"update it ({bmc.get('error message', 'no BMC status available')}).\n"
                 f'Please contact {SUPPORT}.')
    return bmc['version'], bmc['build_info'], bmc['firmware slot'], bmc['pcb rev']


def main():
    parser = argparse.ArgumentParser(description='Check, update or downgrade the BMC firmware of a Time Tagger X.')
    parser.add_argument('firmware', nargs='?',
                        help='BMC firmware file (.bin); without it, the script only shows the current BMC firmware')
    parser.add_argument('--serial', help='serial number of the Time Tagger X, needed if several are connected')
    args = parser.parse_args()

    check_software_version()
    firmware = os.path.abspath(args.firmware) if args.firmware else None
    new_version, new_build = identify_firmware(firmware) if firmware else (None, None)
    serial = select_serial(args.serial)

    with TimeTagger.createTimeTagger(serial) as tagger:
        check_device(tagger)
        old_version, old_build, old_slot, hardware_revision = read_bmc_status(tagger)
        print(f'Time Tagger X {serial}, hardware revision 1.{hardware_revision}')
        print(f'  current BMC firmware: {old_version} (build {old_build}, slot {old_slot})')
        if not firmware:
            print('No firmware file given, so nothing was changed.')
            return
        if old_build not in PUBLISHED_BUILDS:
            sys.exit('This script can only change the BMC firmware of units that run one of the two published '
                     f'firmware versions. Please contact {SUPPORT} to upgrade this unit.')
        if new_version == '2.6' and hardware_revision < MIN_HARDWARE_REVISION_FOR_2_6:
            sys.exit(f'BMC firmware 2.6 is not released for hardware revision 1.{hardware_revision}. '
                     f'Please contact {SUPPORT}.')
        print(f'  new BMC firmware:     {new_version} (build {new_build})')
        if old_build == new_build:
            print('The device already runs this firmware. Nothing was changed.')
            return
        if input("Type 'yes' to flash the new firmware: ").strip().lower() != 'yes':
            print('Cancelled. Nothing was changed.')
            return
        print('Uploading the firmware. Do not disconnect or switch off the device.')
        tagger.updateBMCFirmware(firmware)
    print('Upload finished.\n')

    prompt = ('Now press the power button of the Time Tagger X to switch it to standby (blue light),\n'
              'then unplug the power cable. Wait a few seconds, plug the cable back in and press the\n'
              'power button to switch the device on. The power button alone is not enough.\n'
              'When the power button light is green, press Enter.')
    while True:
        input(prompt)
        prompt = 'Press Enter to try again, or Ctrl+C to stop.'
        try:
            with TimeTagger.createTimeTagger(serial) as tagger:
                version, build, slot, _ = read_bmc_status(tagger)
        except RuntimeError as error:
            print(f'Could not connect to the Time Tagger X {serial}: {error}')
            continue
        if build == old_build:
            print('The device still runs the previous firmware. Switch it to standby, unplug the power cable\n'
                  'for a few seconds, plug it back in and switch the device on again;\n'
                  f'the power button alone is not enough. If this persists, please contact {SUPPORT}.')
            continue
        break

    print(f'BMC firmware now: {version} (build {build}, slot {slot})')
    if (version, build) == (new_version, new_build):
        print('The firmware was changed successfully.')
    else:
        sys.exit(f'The BMC does not report the expected firmware {new_version} (build {new_build}).\n'
                 f'Please contact {SUPPORT} and include the output above.')


if __name__ == '__main__':
    main()
