#! /usr/bin/env python3
import sys
import os

currentDir = os.getcwd()

BEGIN = '#$ IGNORE'
END = '#$ END IGNORE'

while not os.path.isfile(os.path.join(currentDir, '.sync/IgnoreList')):
    currentDir = os.path.abspath(os.path.join(currentDir, '..'))
    if currentDir == os.path.realpath('/'):
        print('Error: Did not find `.sync`-directory above current directory.')
        sys.exit(1)

with open(os.path.join(currentDir, '.sync/IgnoreList'), 'r') as f:
    lineArray = f.read().split('\n')

try:
    before = lineArray[:lineArray.index(BEGIN)]
    after = lineArray[lineArray.index(END) + 1:]
except:
    before = lineArray
    after = ['']


def findRepos(directory, repoArray=[]):
    for file in os.listdir(directory):
        if file.endswith('.syncignore'):
            repoArray.append(directory)
        elif os.path.isdir(os.path.join(directory, file)):
            findRepos(os.path.join(directory, file), repoArray)
        elif file.startswith('.'):
            pass
    return repoArray

newIgnored = findRepos(currentDir)
if len(newIgnored) == 0:
    print('Found no `.syncignore`-files.')
    sys.exit(0)

for index, string in enumerate(newIgnored):
    newIgnored[index] = os.path.join('.', string.replace(currentDir, ''))
print("Ignoring\n.", '\n.'.join(newIgnored))
newIgnored.insert(0, BEGIN)
newIgnored.append(END)

with open(os.path.join(currentDir, '.sync/IgnoreList'), 'w') as f:
    f.write('\n'.join(before + newIgnored + after))
