#!/usr/bin/env python3

import sys
import os.path
import subprocess

import logging

CANARY='/etc/.devkit-service-on-os-update'
OS_UPDATE_SERVICE='devkit-service-os-update'
DEVKIT_SERVICE='steamos-devkit-service'

LOG=logging.getLogger(__name__)

def seppuku():
    # don't use --now here - that would terminate the script!
    subprocess.check_call(f'systemctl disable {OS_UPDATE_SERVICE}', shell=True)
    if not os.path.exists(CANARY):
        # write out the os-release file into the canary to mark the point at which this was finalized
        LOG.info(f'Writing out {CANARY}.')
        open(CANARY, 'w').write(open('/etc/os-release','r').read())

if __name__ == '__main__':
    # in SteamOS <= 3.2, the devkit service is always running
    # in SteamOS > 3.2, the devkit service is enabled/disabled based on the Steam client going into developer mode
    # for OS installs <= 3.2 we need to do a one-time check and disable the service if appropriate

    logging.basicConfig(level=logging.INFO, format='%(message)s')

    if os.path.exists(CANARY):
        LOG.info(f'{CANARY} exists.')
        # this shouldn't happen, but if ths one-off service is still running, disable it again
        seppuku()
        sys.exit(0)

    if os.path.exists( os.path.expanduser( '/home/deck/devkit-game' ) ):
        LOG.info(f'This system has been used as devkit before, making sure {DEVKIT_SERVICE} is enabled.')
        # see https://gitlab.steamos.cloud/jupiter/tasks/-/issues/580#note_56679
        subprocess.check_call(f'systemctl enable --now avahi-daemon && systemctl enable --now {DEVKIT_SERVICE}', shell=True)
        seppuku()
        sys.exit(0)

    cp = subprocess.run(f'systemctl is-active {DEVKIT_SERVICE}', stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, shell=True)
    if cp.returncode != 0:
        LOG.info(f'{DEVKIT_SERVICE} is already inactive, nothing to do.')
        seppuku()
        sys.exit(0)

    LOG.info(f'Disabling {DEVKIT_SERVICE} to meet the new OS configuration (one time).')
    cp = subprocess.run(f'systemctl disable --now {DEVKIT_SERVICE} && systemctl disable --now avahi-daemon', shell=True)
    if cp.returncode == 0:
        # only do this if everything looks fine, give us a chance to run again otherwise
        seppuku()
    sys.exit(cp.returncode)
