import os
import subprocess
import shutil
import platform

# Type of symlink depends on OS
env = platform.system()
print('OS: ' + env)

def create_path(path):
    if env == 'Windows':
        return path
    else:
        return path.replace('\\', '/')

# Path to gitignore
DRIVER_GITIGNORE = "..\\LTSketchbook\\libraries\\.gitignore"

# Path to file with list of drivers we are linking
VALID_ADI_DRIVERS = ".\\ADIDrivers.txt"

# Folders in no-os that we want to search
ADI_DRIVER_LOCATIONS = [
    create_path('device_drivers\\'),
    create_path('drivers\\')
]

# Location of no-os repo
ADI_REPO_LOCATION = create_path('..\\ADIDrivers\\no-os\\')

# Path relative from inside the LTSketchbook libraries driver folders
# to the no-os folder
SYMLINK_PATH_BASE = create_path('..\\..\\ADIDrivers\\no-os\\')

# Path to LTSketchbook libraries folder
LIN_DRIVER_LOCATIONS = create_path('..\\LTSketchbook\\libraries\\')

# Get list of drivers we want to copy
valid_drivers = []
with open(VALID_ADI_DRIVERS) as f:
    valid_drivers = f.readlines()
valid_drivers = [x.strip() for x in valid_drivers]

# Create gitignore
with open(DRIVER_GITIGNORE, 'w+') as f:
    print('\n**********************************')
    print('Creating gitignore at ' + DRIVER_GITIGNORE)
    f.write('#################################################\n')
    f.write('# THIS IS GENERATED BY PYTHON SCRIPT, DO NOT EDIT\n')
    for line in valid_drivers:
        f.write(line + "/\n")

# Error checking
num_created = 0
num_failed = 0

# Iterate through driver folders
for repo_folder in ADI_DRIVER_LOCATIONS:
    full_folder_path = ADI_REPO_LOCATION + repo_folder
    print('\n**********************************')
    print('Searching through ' + full_folder_path)
    # Get part folders in driver folder
    for searchdir, partdirs, filenames in os.walk(full_folder_path):
        # Iterate through parts folders in folder
        for part in partdirs:
            print('  Found part ' + part)
            # Check if we want to copy this part
            if part in valid_drivers:
                # Create symlink paths
                link_dest = SYMLINK_PATH_BASE + repo_folder + part
                link_loc = LIN_DRIVER_LOCATIONS + part

                # Check for & remove existing links
                print('    Checking for previously created link: ' + link_loc)
                if os.path.exists(link_loc):
                    if env == 'Windows':
                        print('      Removing old link using rmdir (win32)')
                        os.rmdir(link_loc)
                    else:
                        print('      Removing old link using unlink (unix)')
                        os.unlink(link_loc)

                print('    Creating symlink to ' + link_dest + ' in ' + link_loc)
                
                # Create the symlink
                if env == 'Windows':
                    result = subprocess.call(['mklink', '/d', link_loc, link_dest], stdout=subprocess.PIPE, universal_newlines=True, shell=True)
                    #print('      ' + result.stdout)
                else:
                    os.symlink(link_dest, link_loc)
            else:
                print('    Part not found in ADIDrivers.txt, skipping')
            
        break

print('Done!')
