"""Installed executable code is readable, never operator-writable."""
import os
from pathlib import Path
import shlex


def launcher(prefix):
    # CTCLR-02: escalate before Python imports inspect protected state paths.
    return ('#!/bin/sh\n'
            'if [ "$(/usr/bin/id -u)" -ne 0 ]; then\n'
            '  if [ "$#" -eq 0 ]; then exec /usr/bin/sudo -k -- /usr/local/bin/ct; fi\n'
            '  exec /usr/bin/sudo -- /usr/local/bin/ct "$@"\n'
            'fi\nexec /usr/bin/python3 '+shlex.quote(str(Path(prefix)/'ct.py'))+' "$@"\n').encode()


def tool_access(prefix):
    prefix = Path(prefix)
    for directory in (prefix.parent, prefix):
        if directory.is_symlink() or not directory.is_dir() or directory.stat().st_uid != os.geteuid():
            raise ValueError('Unsafe tool directory')
        directory.chmod(0o755)
    for path in prefix.rglob('*'):
        if path.is_symlink():
            raise ValueError('Symlink in executable installation')
        if path.is_dir():
            path.chmod(0o755)
