#!/usr/bin/python3
"""Repair only the Native Tablet AX900 storage-mode rule; no package installation."""
import json
import os
from pathlib import Path
import subprocess
import sys
import fcntl

ROOT=Path('/var/lib/native-tablet-ax900')
RULE=Path('/etc/udev/rules.d/79-native-tablet-ax900.rules')
BACKUP=ROOT/'usb-rule-before-mini-fix.txt'
OLD='KERNEL=="sd*", ATTRS{idVendor}=="a69c", ATTRS{idProduct}=="5724", RUN+="/usr/bin/eject /dev/%k"\n'
NEW=''.join('ACTION=="add", SUBSYSTEM=="block", ENV{DEVTYPE}=="disk", KERNEL=="sd*|sr*", ATTRS{idVendor}=="a69c", ATTRS{idProduct}=="'+pid+'", RUN+="/usr/bin/eject /dev/%k"\n' for pid in ('5723','5724'))


def write(text):
    tmp=RULE.with_suffix('.tmp');tmp.write_text(text);tmp.chmod(0o644);tmp.replace(RULE)


def repair(undo=False):
    data=json.loads((ROOT/'state.json').read_text())
    if data.get('phase')!='installed' or not data.get('rule_changed'):
        raise RuntimeError('Zuerst den optionalen AX900-Treiber über das WLAN-Menü installieren.')
    if RULE.is_symlink() or BACKUP.is_symlink():raise RuntimeError('Verknüpfungen werden nicht verändert.')
    old=RULE.read_text()
    if old not in (OLD,NEW):raise RuntimeError('Extern geänderte Regel wird nicht überschrieben.')
    if undo:
        if not BACKUP.exists():print('Dieser Mini-Fix hat keine Änderung zum Zurücknehmen.');return
        target=BACKUP.read_text()
        if target not in (OLD,NEW):raise RuntimeError('Ungültige Regelsicherung.')
    else:
        if old==NEW:print('USB-Regel ist bereits aktuell. Stick abziehen und wieder einstecken.');return
        if not BACKUP.exists():BACKUP.write_text(old);BACKUP.chmod(0o600)
        target=NEW
    try:
        write(target)
        subprocess.run(['udevadm','control','--reload-rules'],check=True)
    except Exception:
        write(old)
        subprocess.run(['udevadm','control','--reload-rules'],check=False)
        raise
    if undo:BACKUP.unlink()
    print('USB-Umschaltregel '+('zurückgenommen.' if undo else 'für 5723 und 5724 repariert.'))
    print('Stick jetzt abziehen und wieder einstecken. Kein Neustart oder Treiberneubau nötig.')
    print('WLAN-Erkennung und dm-Verbindung müssen anschließend geprüft werden.')


def main():
    if os.geteuid()!=0:raise RuntimeError('Administratorrechte erforderlich.')
    if sys.argv[1:] not in ([],['--undo']):raise RuntimeError('Unbekannte Aktion.')
    with (ROOT/'lock').open('a') as lock:
        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        repair('--undo' in sys.argv)


if __name__=='__main__':
    try:main()
    except Exception as error:print('Reparatur abgebrochen: '+str(error));sys.exit(1)
