#!/usr/bin/python3 -I
# SPDX-License-Identifier: MIT
"""Explicit, root-only locale setup launched from the maintenance terminal."""
import fcntl
import os
from pathlib import Path
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parent))
import language_settings

if __name__ == '__main__':
    try:
        if os.geteuid() != 0:
            raise PermissionError('Run language setup through ErdOS Settings with administrator authentication.')
        args = sys.argv[1:]
        with open('/run/erdos-language.lock', 'a') as lock:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            if len(args) == 3 and args[0] == 'apply':
                language_settings.apply_system(*args[1:])
            elif args == ['translations']:
                language_settings.install_translations()
            else:
                raise ValueError('Usage: configure-language {apply LANGUAGE FORMATS|translations}')
    except BlockingIOError:
        print('Another language setup is running. Wait for it to finish and try again.', file=sys.stderr)
        sys.exit(1)
    except Exception as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
