#!/usr/bin/python3
"""Remove localized EmbeddedResource entries from Be.HexEditor.csproj.

Bypasses dpkg-source patch application limitations regarding CRLF line endings
by modifying the XML file directly during the debian/rules execution phase.

The upstream .csproj file uses Windows CRLF line endings, which prevents the
original fixmonocomp.patch from applying cleanly via dpkg-source/patch (patch
strips trailing CRs from the patch text, after which context lines no longer
match the CRLF source).  Applying the equivalent change here at build time
sidesteps the line-ending mismatch entirely.

Original fix by: Mathieu Malaterre <malat@debian.org>
See: http://lists.debian.org/debian-cli/2013/01/msg00000.html
"""

import os
import re
import sys

DEFAULT_CSPROJ = 'sources/Be.HexEditor/Be.HexEditor.csproj'


def main():
    # Allow path override for local execution/testing
    csproj_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_CSPROJ

    if not os.path.exists(csproj_path):
        print(f'Error: Target file not found: {csproj_path}', file=sys.stderr)
        sys.exit(1)

    # Read as pure binary to completely isolate Python from host line-ending logic
    with open(csproj_path, 'rb') as f:
        raw_content = f.read()

    try:
        content = raw_content.decode('utf-8')
    except UnicodeDecodeError:
        # Fallback only if upstream contains invalid UTF-8 bytes
        content = raw_content.decode('utf-8', errors='replace')

    # Remove EmbeddedResource entries for localised .resx files that cause
    # compilation failures under mono on Linux.  Match \r?\n explicitly so the
    # regex works correctly against CRLF source regardless of platform.
    block_re = re.compile(
        r'[ \t]*<EmbeddedResource Include="'
        r'(?:Form\w+\.(?:de|it|ru|zh-Hans)|UCAbout\.(?:de|it|ja|zh-Hans))\.resx'
        r'">\r?\n'
        r'(?:[ \t]*<(?:DependentUpon|SubType)>[^<]*</(?:DependentUpon|SubType)>\r?\n)*'
        r'[ \t]*</EmbeddedResource>\r?\n'
    )

    result, n = block_re.subn('', content)
    if n == 0:
        # Idempotent: don't break incremental rebuilds if run twice without clean
        print(f'{csproj_path}: no matching blocks found; already applied?', file=sys.stderr)
        sys.exit(0)

    # Encode back to bytes: guarantees every \r\n in result stays \r\n on disk
    # regardless of the build environment's newline translation settings.
    output_bytes = result.encode('utf-8')

    # Atomic write: prevents a truncated/corrupted .csproj if the build is
    # interrupted mid-write (disk full, signal, etc.).
    tmp_path = f'{csproj_path}.tmp'
    try:
        with open(tmp_path, 'wb') as f:
            f.write(output_bytes)
        os.replace(tmp_path, csproj_path)
    except Exception as e:
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)
        print(f'Error writing to {csproj_path}: {e}', file=sys.stderr)
        sys.exit(1)

    print(f'{csproj_path}: removed {n} localised EmbeddedResource block(s).')


if __name__ == '__main__':
    main()
