#!/usr/bin/python3

try:
    from os import scandir
    import os 
except ImportError:
    from scandir import scandir  # use scandir PyPI module on Python < 3.5
    import os 

from pathlib import Path
import time
import sys
import re

def scantree(path):
    """Recursively yield DirEntry objects for given directory."""
    for entry in scandir(path):
        if entry.is_dir(follow_symlinks=False):
            if not entry.name.startswith('typo3_src'):
                yield from scantree(entry.path)  # see below for Python 2.x
        else:
            yield entry

if __name__ == '__main__':
    
    counter=0

    for entry in scantree(sys.argv[1] if len(sys.argv) > 1 else '.'):
        if entry.name.startswith('typo3_src') and os.path.islink(entry.path):
                  
            __filename = entry.name
            __filepath = entry.path

            """ Ist der Symlink auch von WHF? """            
            whfTest = re.match('^\/usr\/share\/', os.readlink(entry.path))

            """ Ist es ein Symlink, existiert das Ziel und ist der Link auch von WHF? """
            if os.path.islink(entry.path) and os.path.isdir(entry.path) and whfTest:
                __symlink = os.readlink(entry.path)                

                thePath = Path(__filepath)
                owner = thePath.owner()

                if owner != "root":
                    counter = counter+1
                    print('**** Symlink gehört User: '+owner)

                    user_src = __filepath.split('/')
                    user = user_src[3]

                    
                    print('rm '+ __filepath)
                    #os.system('rm '+ __filepath)

                    print('cp '+ __symlink + ' ' +  __filepath + ' -R')
                    #os.system('cp '+ __symlink + ' ' +  __filepath + ' -R')

                    print('chown ' + user +'. ' +  __filepath + ' -R')
                    #os.system('chown ' + user +'. ' +  __filepath + ' -R')
                    print('\n')
 
                    time.sleep(1)
                else:
                    print('++++ Symlink gehört root: '+__filepath)
                    counter = counter+1
                    user_src = __filepath.split('/')
                    user = user_src[3]
                    
                    print('rm '+ __filepath)
                    #os.system('rm '+ __filepath)

                    print('cp '+ __symlink + ' ' +  __filepath + ' -R')
                    #os.system('cp '+ __symlink + ' ' +  __filepath + ' -R')

                    print('chown ' + user +'. ' +  __filepath + ' -R')
                    #os.system('chown ' + user +'. ' +  __filepath + ' -R')
                    print('\n')

                    time.sleep(1)

    print( str(counter)+" Symlinks ersetzt")

