#!/usr/bin/env python3
"""Deploy guard for projects.timfalken.com repositories.

Shared snippet: copy this file unchanged into ci/ of every repository that
deploys to projects.timfalken.com. It refuses any project directory that would
make a mirror --delete overwrite the whole site (or another project).

Usage in Python:   from deploy_guard import project_dir; path = project_dir(os.environ)
Usage in a shell:  python3 ci/deploy_guard.py   (exit 1 with a clear message on failure)

Values are never printed; only variable names appear in messages.
"""
import posixpath
import re
import sys

ROOT_VAR = 'timftproot'
PROJECT_VAR = 'projectftp'


class DeployGuardError(ValueError):
    pass


def _expand(value, environ):
    """Expand $timftproot / ${timftproot} (GitLab expanded these; 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.strip()
    if not path:
        return ''
    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/<project>.')
    if any(c in raw for c in '\r\n\x00'):
        raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een regeleinde of NUL-byte.')
    if '$' in raw.replace('$' + ROOT_VAR, '').replace('${' + ROOT_VAR + '}', ''):
        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 "."); '
                               f'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); '
                               f'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}.')
    return norm


def main(environ=None):
    import os
    try:
        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.')
    return 0


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