import os
import sys
import shutil
import platform

print('!!!!!!!!!! WARNING !!!!!!!!!!')
print('You should use GenerateADISymlinks instead.')
print('To force continue type \'yes\':')
if(input() == 'yes'):
    print('Continuing')
else:
    print('Exiting')
    sys.exit()

env = platform.system()
print('OS: ' + env)

def create_path(path):
    path_words = path.split()
    new_path = os.path.join(*path_words)
    return new_path

def upper_file(filename):
    split = str.rpartition(filename, '.')
    uppered = str.upper(split[0]) + split[1] + split[2]
    #print('    Renaming ' + filename + ' to ' + uppered)
    return uppered

DRIVER_GITIGNORE = "../LTSketchbook/libraries/.gitignore"
VALID_ADI_DRIVERS = "./ADIDrivers.txt"

ADI_DRIVER_LOCATIONS = [
    '../ADIDrivers/no-os/device_drivers',
    '../ADIDrivers/no-os/drivers'
    ]

LIN_DRIVER_LOCATIONS = '../LTSketchbook/libraries'

# Convert paths to OS-specific paths
lin_driver_path = create_path(LIN_DRIVER_LOCATIONS)
adi_driver_paths = []
for s in ADI_DRIVER_LOCATIONS:
    adi_driver_paths.append(create_path(s))

# 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")

# Iterate through driver folders
for adi_path in adi_driver_paths:
    print('\n**********************************')
    print('Searching through ' + adi_path)
    for searchdir, partdirs, filenames in os.walk(adi_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 source path
                adi_part_path = os.path.join(adi_path, part)
                # Create destination path
                lin_part_path = os.path.join(lin_driver_path, str.upper(part))
                if not os.path.exists(lin_part_path):
                    os.makedirs(lin_part_path)
                # Iterate through files in source path
                for partdir, subpartdirs, partfiles in os.walk(adi_part_path):
                    for partfile in partfiles:
                        src_path = os.path.join(adi_part_path, partfile)
                        dst_path = os.path.join(lin_part_path, upper_file(partfile))
                        shutil.copy2(src_path, dst_path)
                        print('    Copying ' + src_path + ' to ' + dst_path)
                    break
            else:
                print('    Part not found in ADIDrivers.txt, skipping')
        break

print('Done!')