#!/usr/bin/env python
"""Fix Python-based executables so that they are run with a framework build"""
from argparse import ArgumentParser
from distutils.spawn import find_executable
import re


NEW = '/python.app/Contents/MacOS/python'

argparser = ArgumentParser(description=__doc__)
argparser.add_argument('exe', type=str, nargs='?', default='eelbrain', help="Name of the executable to fix")

if __name__ == '__main__':
    args = argparser.parse_args()

    path = find_executable(args.exe)

    with open(path) as fid:
        text = fid.read()

    text_sub, n = re.subn(r"/bin/python(?:\d\.\d)?$", NEW, text, flags=re.MULTILINE)
    if n != 1:
        raise RuntimeError(f"Found {n} instances of path in:\n\n{text}")

    with open(path, 'w') as fid:
        fid.write(text_sub)
