#!/usr/bin/env python3
"""Deploy guard: expand $timftproot, refuse a deploy that would hit the FTP root."""
import posixpath
import re
import sys

ROOT_VAR = 'timftproot'
PROJECT_VAR = 'projectftp'
ALLOWED_LEAF = 'allianties'


class DeployGuardError(ValueError):
    pass


def _expand(value, environ):
    """Expand $timftproot / ${timftproot} (BlueGit secrets do not)."""
    root = environ.get(ROOT_VAR) or ''
    return re.sub(r'\$\{?' + ROOT_VAR + r'\}?', lambda _m: root, value)


def _norm(path):
    path = (path or '').strip()
    if not path:
        return ''
    # Collapse duplicate slashes before and after normpath.
    path = re.sub(r'/+', '/', path.replace('\\', '/'))
    norm = posixpath.normpath(path)
    return '/' if norm in ('/', '//', '.') else norm.rstrip('/') or '/'


def project_dir(environ):
    raw = environ.get(PROJECT_VAR)
    if raw is None:
        raise DeployGuardError(
            f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is niet gezet. '
            f'Zet de projectmap als project-secret, bijvoorbeeld $timftproot/{ALLOWED_LEAF}.'
        )
    if any(c in raw for c in '\r\n\x00'):
        raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een regeleinde of NUL-byte.')
    leftover_dollar = raw.replace('$' + ROOT_VAR, '').replace('${' + ROOT_VAR + '}', '')
    if '$' in leftover_dollar:
        raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een onbekende $-verwijzing.')
    if (('$' + ROOT_VAR) in raw or ('${' + ROOT_VAR + '}') in raw) and not (environ.get(ROOT_VAR) or '').strip():
        raise DeployGuardError(
            f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} verwijst naar {ROOT_VAR}, maar die is niet gezet.'
        )
    value = _expand(raw, environ).strip()
    if not value:
        raise DeployGuardError(f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is leeg.')
    parts = [p for p in value.replace('\\', '/').split('/') if p]
    if '..' in parts:
        raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag geen ".." bevatten.')
    if value.startswith('~'):
        raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag niet de thuismap (~) zijn.')
    norm = _norm(value)
    if norm in ('/', '.', ''):
        raise DeployGuardError(
            f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} wijst naar de root ("/" of "."); '
            'dat zou de hele website overschrijven.'
        )
    root = _norm(environ.get(ROOT_VAR) or '')
    if root and norm == root:
        raise DeployGuardError(
            f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} is gelijk aan {ROOT_VAR} (de FTP-root van de site); '
            'dat zou de hele website overschrijven.'
        )
    if root and root not in ('/', '.') and norm.startswith('/') and not norm.startswith(root + '/'):
        raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} ligt niet onder {ROOT_VAR}.')
    leaf = parts[-1].lower() if parts else ''
    if leaf != ALLOWED_LEAF:
        raise DeployGuardError(
            f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} moet op "{ALLOWED_LEAF}" eindigen (leaf={leaf!r}).'
        )
    return norm


def main(environ=None):
    import os
    try:
        path = project_dir(os.environ if environ is None else environ)
    except DeployGuardError as error:
        print(str(error), file=sys.stderr)
        return 1
    print('Deploy guard: projectmap ok.')
    # Path itself is not printed (secrets). Length only.
    print('projectftp length=%d' % len(path))
    return 0


if __name__ == '__main__':
    sys.exit(main())
