#!/usr/bin/env nix-shell
#!nix-shell -i python -p python3

# NOTE: the colors are used to keep track of which letters have been
#       already substituted, and which are still unknown.

def green(s):
    return f"\033[42m{s}\033[0m"

def red(s):
    return f"\033[41m{s}\033[0m"

def substitute(cipher_text, substitution_map):
    for letter in cipher_text:
        if letter.lower() in substitution_map:
            if letter.isupper():
                x = substitution_map[letter.lower()].upper()
            else:
                x = substitution_map[letter]
            print(green(x), end="")
        else:
            print(red(letter), end="")

with open('message.txt', 'r') as file:
    enc = file.read()

# Here, I will be slowly substituting the letters in the ciphertext
# based on what I believe the words to be. I have commented out the
# invocations of substitute, and commented the newly found letters
# after each invocation.

# Starting off, "pvncDCM{...}" looks like "picoCTF{...}"

substitution_map = {
    '0': '0',
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
    '7': '7',
    '8': '8',
    '9': '9',
    '-': '-',
    '_': '_',
    '\n': '\n',
    ' ': ' ',
    ',': ',',
    '.': '.',
    ':': ':',
    ';': ';',
    '{': '{',
    '}': '}',
    'p': 'p',
    'v': 'i',
    'n': 'c',
    'c': 'o',
    'd': 't',
    'm': 'f',
}

# substitute(enc, substitution_map)

# 'Dsu fxow ij' -> 'The flag is'

substitution_map['d'] = 't'
substitution_map['s'] = 'h'
substitution_map['u'] = 'e'
substitution_map['x'] = 'l'
substitution_map['o'] = 'a'
substitution_map['w'] = 'g'
substitution_map['j'] = 's'

# substitute(enc, substitution_map)

# 'taligg all thiggs igto cogsifeaatiog' -> 'taking all things into consideration'
# 'rhich' -> 'which'

substitution_map['l'] = 'k'
substitution_map['g'] = 'n'
substitution_map['f'] = 'd'
substitution_map['a'] = 'r'
substitution_map['r'] = 'w'

# substitute(enc, substitution_map)

# 'roynd hlack spots' -> 'round black spots'
# 'ekceedinglq' -> 'exceedingly'

substitution_map['y'] = 'u'
substitution_map['h'] = 'b'
substitution_map['q'] = 'y'
substitution_map['k'] = 'x'

# substitute(enc, substitution_map)

# 'iery reearkable' -> 'very remarkable'
# 'pribe' -> 'pride'
# 'Zupiter' -> 'Jupiter'

substitution_map['i'] = 'v'
substitution_map['e'] = 'm'
substitution_map['b'] = 'd'
substitution_map['z'] = 'j'

substitute(enc, substitution_map)