#!/usr/bin/env python
#
# pd-powerkey.py - monitor GPIO to detect power key press from Power MCU (PCU)
#

import time,os,sys
os.chdir('/storage/scripts/pidesktop/')
sys.path.append('/storage/.kodi/addons/virtual.rpi-tools/lib') # Import gpiozero from Raspberry Pi Tools add-on
from gpiozero import Button,LED

print("pidesktop: power button service initializing")

pwrBtn = Button(13) # PCU to Pi - detect power key pressed

pcu = LED(6) # Pi to PCU - start/stop shutdown timer
pcu.off() # tell PCU we are alive
pcu.on() # cause blink by starting shutdown timer
time.sleep(0.5)
pcu.off() # clear timer to stop blinking and prefent forced power off

# callback function
def powerkey_pressed(channels):
    print("pidesktop: power button press detected, initiating shutdown")
    os.system("sync")
    # os.system("shutdown -h now") # Shutdown the OS directly (forced shutdown)
    os.system("kodi-send --action=ShutDown") # Tell Kodi to execute it's shutdown procedure (graceful)
    sys.exit()

pwrBtn.when_released = powerkey_pressed # Setup callback for the power off signal
print("pidesktop: power button monitor enabled")

while True: # Keep the service running
    time.sleep(10)
