#!/usr/bin/env python3

"""Sanitize potentially identifying 'fingerprinting' characters.

optional: files with country-specific spellings in the same directory
          comes with: US.safetext and UK.safetext

---
see: https://github.com/DavidJacobson/SafeText
"""

import argparse
import fileinput
import os
import sys
from glob import iglob

version = "safetext 0.1"
spellsuffix = "safetext"

ZERO_WIDTH_CHARS = {
    "SPACE": "\u200b",
    "NON-JOINER CODE POINT": "\u200c",
    "JOINER CODE POINT": "\u200d",
    "NO BREAK SPACE CODE POINT": "\ufeff",
    "RIGHT LEFT MARK": "\u200f",
    "LEFT RIGHT MARK": "\u200e",
}
NON_STANDARD_SPACES = {
    "EN QUAD": "\u2000",
    "HAIR SPACE": "\u200a",
    "NARROW NO BREAK SPACE": "\u202f",
    "MEDIUM MATHEMATICAL SPACE": "\u205f",
    "EN SPACE": "\u2002",
    "EM SPACE": "\u2003",
    "THREE PER EM SPACE": "\u2004",
    "FOUR PER EM SPACE": "\u2005",
    "SIX PER EM SPACE": "\u2006",
    "FIGURE SPACE": "\u2007",
    "PUNCTUATION SPACE": "\u2008",
    "THIN SPACE": "\u2009",
    "<> (IS)": "\u3000",
}
HOMOGLYPHS = {  # From https://en.wikipedia.org/wiki/IDN_homograph_attack
    "Cyrillic a": "а",
    "Cyrillic small b": "ь",
    "Cyrillic large b": "Ъ",
    "Cyrillic c": "с",
    "Cyrillic d": "ԁ",
    "Cyrillic e": "е",
    "Cyrillic small h": "һ",
    "Cyrillic large h": "Һ",
    "Cyrillic i": "і",
    "Cyrillic j": "ј",
    "Cyrillic o": "о",
    "Cyrillic p": "р",
    "Cyrillic s": "ѕ",
    "Cyrillic small v": "ѵ",
    "Cyrillic large v": "Ѵ",
    "Cyrillic x": "х",
    "Cyrillic y": "у",
    "Cyrillic A": "А",
    "Cyrillic small B": "в",
    "Cyrillic large B": "В",
    "Cyrillic small C": "с",
    "Cyrillic large C": "С",
    "Cyrillic E": "Е",
    "Cyrillic small F": "ғ",
    "Cyrillic large F": "Ғ",
    "Cyrillic small G": "ԍ",
    "Cyrillic large G": "Ԍ",
    "Cyrillic small H": "н",
    "Cyrillic large H": "Н",
    "Cyrillic I": "І",
    "Cyrillic J": "Ј",
    "Cyrillic small K": "к",
    "Cyrillic large K": "К",
    "Cyrillic small M": "м",
    "Cyrillic large M": "М",
    "Cyrillic small O": "о",
    "Cyrillic large O": "О",
    "Cyrillic P": "Р",
    "Cyrillic S": "Ѕ",
    "Cyrillic small T": "т",
    "Cyrillic large T": "Т",
    "Cyrillic X": "Х",
    "Cyrillic Y": "У",
    "Cyrillic 3": "З",
    "Cyrillic 4": "Ч",
    "Cyrillic 6": "б",
    "Greek c": "ϲ",
    "Greek i": "ί",
    "Greek o": "ο",
    "Greek p": "ρ",
    "Greek w": "ω",
    "Greek v": "ν",
    "Greek A": "Α",
    "Greek B": "Β",
    "Greek C": "Ϲ",
    "Greek E": "Ε",
    "Greek H": "Η",
    "Greek I": "Ι",
    "Greek J": "Ϳ",
    "Greek small K": "Κ",
    "Greek large K": "κ",
    "Greek small M": "Μ",
    "Greek large M": "Ϻ",
    "Greek N": "Ν",
    "Greek O": "Ο",
    "Greek T": "Τ",
    "Greek U": "υ",
    "Greek X": "Χ",
    "Greek Y": "Υ",
    "Greek Z": "Ζ",
    "Armenian g": "ց",
    "Armenian o": "օ",
    "Armenian j": "յ",
    "Armenian h": "հ",
    "Armenian n": "ո",
    "Armenian u": "ս",
    "Armenian q": "զ",
    "Armenian L": "Լ",
    "Armenian O": "Օ",
    "Armenian U": "Ս",
    "Armenian S": "Տ",
    "Armenian 2": "Ձ",
    "Armenian ALT 2": "շ",
    "Armenian 3": "Յ",
    "Armenian 4": "վ",
    "Hebrew i": "וֹ",
    "Hebrew n": "ח",
    "Hebrew O": "ס",
    "Script i": "í",
}


def underline(chars):
    return "\033[4m" + chars + "\033[0m"


def err(s):
    print(s, file=sys.stderr)


parser = argparse.ArgumentParser(
    add_help=False, description="Sanitize potentially identifying invisible characters"
)
parser.add_argument(
    "--notext", "-n", action="store_true", help="Don't display sanitized text"
)
parser.add_argument("--help", "-h", action="help", help="Show this help text")
parser.add_argument(
    "--version", "-V", action="version", version=version, help="Display version"
)
if sys.stdin.isatty():
    parser.add_argument("file", nargs="?", help="Input file to sanitize")
    args = parser.parse_args()
else:
    args = parser.parse_args()
    args.file = "/dev/stdin"


country_dics = {}
cwd = os.getcwd()
path = os.path.dirname(os.path.realpath(__file__))
os.chdir(path)
for dic in iglob("*." + spellsuffix):
    country_dics.update({dic: []})
    with open(dic) as file:
        lines = file.readlines()
        for each in lines:
            country_dics[dic].append(each.strip())
os.chdir(cwd)

found, i, out = 0, 0, ""
for line in fileinput.input(args.file):
    i += 1
    display = line
    for character in ZERO_WIDTH_CHARS:
        if ZERO_WIDTH_CHARS[character] in line:
            err("--- Found invisible {} on line {}:".format(character.lower(), i))
            display = display.replace(ZERO_WIDTH_CHARS[character], underline("*"))
            line = line.replace(ZERO_WIDTH_CHARS[character], "")
    for letter in HOMOGLYPHS:
        if HOMOGLYPHS[letter] in line:
            err("--- Found '{}' on line {}:".format(letter, i))
            display = display.replace(HOMOGLYPHS[letter], underline(HOMOGLYPHS[letter]))
            line = line.replace(HOMOGLYPHS[letter], letter[-1])
    for space in NON_STANDARD_SPACES:
        if NON_STANDARD_SPACES[space] in line:
            err("--- Found non-standard space on line {}:".format(i))
            display = display.replace(NON_STANDARD_SPACES[space], underline(" "))
            line = line.replace(NON_STANDARD_SPACES[space], " ")
    if display != line:
        found += 1
        err(display.strip())
    out += line

    for dic in country_dics:
        for word in country_dics[dic]:
            if word in line.lower():
                err(
                    "--- {} spelling of '{}' on line {}:".format(
                        dic.split(".")[0], word, i
                    )
                )

plural = ""
if found != 1:
    plural = "s"
err(
    "+++ Found {} line{} with potentially 'fingerprinting' characters\n".format(
        found, plural
    )
)

if not args.notext:
    print(out.strip())
if found:
    sys.exit(1)
else:
    sys.exit(0)
