#!/usr/bin/env python3
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#

import sys
import subprocess
from pathlib import Path
import argparse

tuhi_server = Path('/usr/libexec/tuhi', 'tuhi-server')
tuhi_gui = Path('/usr/libexec/tuhi', 'tuhi-gui')


  # NOQA

if __name__ == '__main__':
    if sys.version_info < (3, 6):
        sys.exit('Python 3.6 or later required')

    parser = argparse.ArgumentParser(description='Tuhi')
    parser.add_argument('--flatpak-compatibility-mode',
                        help='Use the flatpak xdg directories',
                        action='store_true',
                        default=False)
    ns, remainder = parser.parse_known_args()
    if ns.flatpak_compatibility_mode:
        import os

        basedir = Path.home() / '.var' / 'app' / 'org.freedesktop.Tuhi'
        print(f'Using flatpak xdg dirs in {basedir}')
        os.environ['XDG_DATA_HOME'] = os.fspath(basedir / 'data')
        os.environ['XDG_CONFIG_HOME'] = os.fspath(basedir / 'config')
        os.environ['XDG_CACHE_HOME'] = os.fspath(basedir / 'cache')

    tuhi = subprocess.Popen([tuhi_server] + remainder)
    try:
        subprocess.run([tuhi_gui] + remainder)
    except KeyboardInterrupt:
        pass
    tuhi.terminate()
