#!/usr/bin/python3

# created based on implementation from HandyGCCS https://github.com/ShadowBlip/HandyGCCS/blob/10bf0da2bbe06b4e6c608e157f26628b6d848042/src/handycon/utilities.py#L351

import evdev
import threading
import os
import subprocess
from time import sleep

POWER_BUTTON_PRIMARY = "LNXPWRBN/button/input0"
POWER_BUTTON_SECONDARY = "PNP0C0C/button/input0"

user = None
home_path = None
powerbuttondevice = None
powerbuttondevice2 = None
longpresstimer = None

def is_game_mode():
    global home_path
    # Get the currently running Steam PID.
    steampid_path = home_path + '/.steam/steam.pid'
    pid = None
    try:
        with open(steampid_path) as f:
            pid = f.read().strip()
    except Exception as e:
        print(f"steam-powerbuttond: failed to get steam PID: {e}")
        return False

    steam_cmd_path = f"/proc/{pid}/cmdline"
    if not os.path.exists(steam_cmd_path):
        # Steam not running.
        return False

    try:
        with open(steam_cmd_path, "rb") as f:
            steam_cmd = f.read()
    except Exception as e:
        print(f"steam-powerbuttond: failed to get steam cmdline: {e}")
        return False 

    # Use this and line to determine if Steam is running in DeckUI mode.
    is_deck_ui = b"-gamepadui" in steam_cmd
    if not is_deck_ui:
        return False
    return True

def get_user():
    global user
    global home_path
    command = "who | awk '{print $1}' | sort | head -1"

    while not user:
        usrs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell=True)
        for first_user in usrs.stdout:
            name = first_user.decode().strip()
            if name is not None:
                user = name
                home_path = f"/home/{user}"
            break
        sleep(1)

def run_steam_command(command):
    global home_path
    steam_path = home_path + '/.steam/root/ubuntu12_32/steam'
    try:
        result = subprocess.run(["su", user, "-c", f"{steam_path} -ifrunning {command}" ])
        return result.returncode == 0
    except Exception as e:
        print('steam-powerbuttond: failed to run steam command: {e}')
        return False

devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
for device in devices:
    if device.name == 'Power Button' and device.phys == POWER_BUTTON_PRIMARY:
        powerbuttondevice = device
        powerbuttondevice.grab()
        print ( "steam-powerbuttond: power button 1 found!" )
    elif device.name == 'Power Button' and device.phys == POWER_BUTTON_SECONDARY:
        powerbuttondevice2 = device
        powerbuttondevice2.grab()
        print ( "steam-powerbuttond: power button 2 found!" )
    else:
        device.close()

get_user()

def longpress():
    global longpresstimer
    longpresstimer = None
    run_steam_command("steam://longpowerpress")


if powerbuttondevice != None or powerbuttondevice2 != None:
    power_button = powerbuttondevice or powerbuttondevice2
    for event in power_button.read_loop():
        if event.type == evdev.ecodes.EV_KEY and event.code == 116: # KEY_POWER
            if event.value == 1:
                longpresstimer = threading.Timer( 1.0, longpress )
                longpresstimer.start()
            elif event.value == 0:
                if longpresstimer != None:
                    if(is_game_mode()):
                         run_steam_command("steam://shortpowerpress")
                    else:
                        os.system('systemctl suspend')
                    longpresstimer.cancel()
                    longpresstimer = None
    if powerbuttondevice:
        powerbuttondevice.close()
    if powerbuttondevice2:
        powerbuttondevice2.close()
    exit()

print ( "steam-powerbuttond: Can't find device for power button!" )
