# See https://github.com/kolunmi/bazaar/blob/main/docs/overview.md#hooks

import os, subprocess, sys

unix_timestamp      = os.getenv('BAZAAR_HOOK_INITIATED_UNIX_STAMP')
unix_timestamp_usec = os.getenv('BAZAAR_HOOK_INITIATED_UNIX_STAMP_USEC')

hook_id            = os.getenv('BAZAAR_HOOK_ID')
hook_type          = os.getenv('BAZAAR_HOOK_TYPE')
was_aborted        = os.getenv('BAZAAR_HOOK_WAS_ABORTED')
dialog_id          = os.getenv('BAZAAR_HOOK_DIALOG_ID')
dialog_response_id = os.getenv('BAZAAR_HOOK_DIALOG_RESPONSE_ID')

non_transaction_appid = os.getenv('BAZAAR_APPID')
transaction_appid     = os.getenv('BAZAAR_TS_APPID')
transaction_type      = os.getenv('BAZAAR_TS_TYPE')

stage     = os.getenv('BAZAAR_HOOK_STAGE')
stage_idx = os.getenv('BAZAAR_HOOK_STAGE_IDX')

# ---

def spawn_and_detach(args):
    subprocess.Popen(args, start_new_session=True, stdout=subprocess.DEVNULL)

def spawn_ujust(id):
    spawn_and_detach(['flatpak-spawn', '--host', 'xdg-terminal-exec', '-x', f'ujust {id}'])

def spawn_brew(app):
    brew = '/home/linuxbrew/.linuxbrew/bin/brew'
    spawn_and_detach([
        'flatpak-spawn', '--host', 'xdg-terminal-exec', '-x',
        'bash', '-c', f'{brew} install --cask {app}'
    ])

def handle_jetbrains():

    def appid_is_jetbrains(appid):
        return appid.startswith('com.jetbrains.') or appid == ('com.google.AndroidStudio')

    match stage:
        case 'setup':
            if transaction_type == 'install' and appid_is_jetbrains(transaction_appid):
                return 'ok'
            else:
                return 'pass'

        case 'setup-dialog':
            return 'ok'

        case 'teardown-dialog':
            if dialog_response_id == 'run-ujust':
                return 'ok'
            else:
                return 'abort'

        case 'catch':
            return 'abort'

        case 'action':
            try:
                spawn_ujust('install-jetbrains-toolbox')
            except:
                pass
            return ''

        case 'teardown':
            # always prevent installation of JetBrains flatpaks
            return 'deny'

def handle_code():

    def appid_is_code(appid):
        return appid == ('com.visualstudio.code') or appid == ('com.vscodium.codium')

    match stage:
        case 'setup':
            if transaction_type == 'install' and appid_is_code(transaction_appid):
                return 'ok'
            else:
                return 'pass'

        case 'setup-dialog':
            return 'ok'

        case 'teardown-dialog':
            if dialog_response_id == 'download':
                return 'ok'
            else:
                return 'abort'

        case 'catch':
            return 'abort'

        case 'action':
            try:
                if transaction_appid == ('com.vscodium.codium'):
                    spawn_brew('ublue/tap/vscodium-linux')
                else:
                    spawn_brew('ublue/tap/visual-studio-code-linux')
            except:
                pass
            return ''

        case 'teardown':
            return 'deny'

# ---

response = 'pass'
match hook_id:
    case 'jetbrains-toolbox':
        response = handle_jetbrains()
    case 'code':
        response = handle_code()

print(response)
sys.exit(0)
