#!/usr/bin/python3

# vi: filetype=python

import re
import sys
import os
import subprocess
import argparse
import logging

from typing import (Any,)

logger = logging.getLogger(__name__)


def run() -> None:
    logging.basicConfig(level=logging.INFO)

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--device',
    )

    options = parser.parse_args()

    DEVICES : dict[str, Any] = dict(
            applesmc=dict(
                devpath='sys/devices/platform/applesmc.768',
                node='/sys/devices/platform/applesmc.768/fan1_manual',
                cmd=r'''
                    chown root:fan /sys/devices/platform/applesmc.768/fan1_*
                    chmod g+w /sys/devices/platform/applesmc.768/fan1_*
                ''',
            ),
            intel_pstate=dict(
                devpath=r'/?sys/devices/system/cpu/cpu0',
                node='/sys/devices/system/cpu/intel_pstate/no_turbo',
                cmd=r'''
                    chown root:fan /sys/devices/system/cpu/intel_pstate/no_turbo
                    chown root:fan /sys/devices/system/cpu/intel_pstate/max_perf_pct
                    #chown root:fan /sys/devices/system/cpu/intel_pstate/status
                    chmod g+w /sys/devices/system/cpu/intel_pstate/no_turbo
                    chmod g+w /sys/devices/system/cpu/intel_pstate/max_perf_pct
                    #chmod g+w /sys/devices/system/cpu/intel_pstate/status
                    echo passive > /sys/devices/system/cpu/intel_pstate/status
                    chown root:fan /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
                    chown root:fan /sys/devices/system/cpu/cpu*/cpufreq/scaling_max_freq
                    chmod g+w /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
                    chmod g+w /sys/devices/system/cpu/cpu*/cpufreq/scaling_max_freq
                ''',
            ),
            #governor=dict(
            #    devpath=r'/?sys/devices/system/cpu/cpu(\d+)',
            #    node=r'/sys/devices/system/cpu/cpu{0}/cpufreq/scaling_governor',
            #    cmd=r'''
            #        chown root:fan /sys/devices/system/cpu/cpu{0}/cpufreq/scaling_governor
            #        chown root:fan /sys/devices/system/cpu/cpu{0}/cpufreq/scaling_max_freq
            #        chmod g+w /sys/devices/system/cpu/cpu{0}/cpufreq/scaling_governor
            #        chmod g+w /sys/devices/system/cpu/cpu{0}/cpufreq/scaling_max_freq
            #    ''',
            #),
    )

    processed : int = 0

    logger.info(dict(device=options.device))

    for k, v in DEVICES.items():
        devpath = re.compile(v['devpath'])

        devpath_m = devpath.match(options.device)

        if devpath_m is None:
            continue

        node_2 = v['node'].format(*devpath_m.groups())

        # logger.info(dict(devpath_m=devpath_m, node=node_2))

        while not os.path.exists(node_2):
            #continue
            time.sleep(1)

        cmd_2 = v['cmd'].format(*devpath_m.groups())

        subprocess.check_call(cmd_2, shell=True)

        logger.info(dict(
            devpath_m=devpath_m,
            node_2=node_2,
            cmd_2=cmd_2,
            msg='processed',
            label=k,
        ))

        processed += 1

    if processed == 0:
        raise NotImplementedError

if __name__ == '__main__':
    run()
