#!/usr/bin/env python3

import os
import sys
import re
import time
from datetime import datetime, timedelta

"""
@file     poweroffconf
@brief    Control de parada tras tiempo de inactividad para ahorro de energía.
@param    int_minutos    Minutos de inactividad (opcional); "no" para deshabilitar.
@note     La comprobación periódica debe ejecutarse en el "cron" del sistema.
@note     Fichero de configuración: /etc/poweroff.conf
@version  1.0.5: incluir opción para deshabilitar ahorro de energía.
@version  1.1.1: Corregir problema al cambiar de día
"""


OPENGNSYS = os.getenv('OPENGNSYS', '/opt/opengnsys')
OGETC = os.getenv('OGETC', f'{OPENGNSYS}/etc')
POWEROFFCONF = '/etc/poweroff.conf'

def ogRaiseError(error_code, message):
    print(f"Error {error_code}: {message}", file=sys.stderr)
    sys.exit(1)

if not os.path.isfile(POWEROFFCONF):
    ogRaiseError('OG_ERR_NOTFOUND', POWEROFFCONF)

config = {}
with open(POWEROFFCONF) as f:
    for line in f:
        name, var = line.partition("=")[::2]
        config[name.strip()] = str(var).strip()

POWEROFFSLEEP = config.get('POWEROFFSLEEP')
POWEROFFTIME = config.get('POWEROFFTIME')

if len(sys.argv) == 1:
    if not POWEROFFSLEEP:
        ogRaiseError('OG_ERR_FORMAT', "Sin tiempo de espera.")
elif len(sys.argv) == 2:
    POWEROFFSLEEP = sys.argv[1]
    if POWEROFFSLEEP == "no":
        POWEROFFSLEEP = ""
    elif not re.match(r'^\d*$', POWEROFFSLEEP):
        ogRaiseError('OG_ERR_FORMAT', 'Parámetro debe ser núm. minutos o "no" para deshabilitar.')
    
    with open(POWEROFFCONF, 'r') as file:
        data = file.read()
    data = re.sub(r'POWEROFFSLEEP=.*', f'POWEROFFSLEEP={POWEROFFSLEEP}', data)
    with open(POWEROFFCONF, 'w') as file:
        file.write(data)
    
    if POWEROFFSLEEP:
        POWEROFFTIME = int((datetime.now() + timedelta(minutes=int(POWEROFFSLEEP))).timestamp())
        with open(POWEROFFCONF, 'r') as file:
            data = file.read()
        data = re.sub(r'POWEROFFTIME=.*', f'POWEROFFTIME={POWEROFFTIME}', data)
        with open(POWEROFFCONF, 'w') as file:
            file.write(data)
    sys.exit(0)
else:
    ogRaiseError('OG_ERR_FORMAT', f"Formato: {sys.argv[0]} [int_minutos | no]")

pgrep_output = os.popen('pgrep -fa 2>&1').read()
if 'invalid' in pgrep_output:
    PGREP = 'pgrep -fl'
else:
    PGREP = 'pgrep -fa'

pgrep_result = os.popen(f'{PGREP} {OPENGNSYS}').read()
if re.search(f'{OGETC}|{sys.argv[0]}', pgrep_result) is None:
    with open(POWEROFFCONF, 'r') as file:
        data = file.read()
    data = re.sub(r'POWEROFFTIME=.*', 'POWEROFFTIME=', data)
    with open(POWEROFFCONF, 'w') as file:
        file.write(data)
else:
    NOW = int(time.time())
    if not POWEROFFTIME:
        POWEROFFTIME = int((datetime.now() + timedelta(minutes=int(POWEROFFSLEEP))).timestamp())
        with open(POWEROFFCONF, 'r') as file:
            data = file.read()
        data = re.sub(r'POWEROFFTIME=.*', f'POWEROFFTIME={POWEROFFTIME}', data)
        with open(POWEROFFCONF, 'w') as file:
            file.write(data)
    else:
        if NOW >= int(POWEROFFTIME):
            os.system(f'{OPENGNSYS}/scripts/poweroff')