#!/usr/bin/env python3

import sys
import os
import shutil

def inplace_change(filename, old_string, new_string):
    # Safely read the input filename using 'with'
    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print ('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    # Safely write the changed content, if found in the file
    with open(filename, 'w') as f:
        print ('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)


dic = []

for datapath in ['data', 'cfg']:
    for root, dirs, files in os.walk(datapath, topdown=True):
        for name in files:
            dic.append(os.path.join(root, name))

for codepath in ['cfg', 'python', 'src', 'examples']:
    for root, dirs, files in os.walk(codepath, topdown=True):
        for name in files:
            if name.endswith(".debsave1"):
                continue
            for d in dic:
                if d in open(os.path.join(root,name)).read():
                    if not os.path.isfile(os.path.join(root, name+".debsave1")):
                        shutil.copy2(os.path.join(root, name), os.path.join(root, name+".debsave1"))
                    inplace_change(os.path.join(root, name), d, os.path.join('/', 'usr', 'share', 'darknet', d))

