# Original source: https://gist.github.com/xesscorp/8a2ed1b8923f04ae6366
# Edit by Jarek Paral <paral@robotikabrno.cz>
# Further edits by Petr Malanik <Malanik.Petr.gm@gmail.com>

#
# KiCad outputs Gerber files with extensions that aren't recognized by the most commonly used
# PCB manufacturers. This Python script renames the files to what want manufactory Gatema for
# (company in Czech Republic which produce PCB - http://www.gatema.cz) Pool servis - prototype PCB
# (http://pcb.gatema.cz/kriteria-dat-pro-pool-servis/).
# Just execute this script in your KiCad project directory and the Gerber files will be renamed.
# Export gerbers with Protell filenames

import glob
import os

# Make a list of .gbr and .drl files in the current directory.
gerbers = glob.glob('*.gbr')
gerbers.extend(glob.glob('*.gbo'))
gerbers.extend(glob.glob('*.gbs'))
gerbers.extend(glob.glob('*.gbl'))
gerbers.extend(glob.glob('*.gtl'))
gerbers.extend(glob.glob('*.gts'))
gerbers.extend(glob.glob('*.gto'))
gerbers.extend(glob.glob('*.gm1'))

gerbers.extend(glob.glob('*.drl'))

# File renaming rules.
gerber_types = [
    {'from': '-B_Silkscreen.gbo',   'to': '-B_Silkscreen.gbo.plb'},
    {'from': '-B_Mask.gbs',         'to': '-B_Mask.gbs.smb'},
    {'from': '-B_Cu.gbl',           'to': '-B_Cu.gbl.bot'},
    {'from': '-In1_Cu.gbr',         'to': '-In1_Cu.gbr.in2'},
    {'from': '-In2_Cu.gbr',         'to': '-In2_Cu.gbr.in3'},
    {'from': '-In1_Cu.g2',          'to': '-In1_Cu.g2.in2'},
    {'from': '-In2_Cu.g3',          'to': '-In2_Cu.g3.in3'},
    {'from': '-F_Cu.gtl',           'to': '-F_Cu.gtl.top'},
    {'from': '-F_Mask.gts',         'to': '-F_Mask.gts.smt'},
    {'from': '-F_Silkscreen.gto',   'to': '-F_Silkscreen.gto.plt'},
    {'from': '-Edge_Cuts.gm1',      'to': '-Edge_Cuts.gko.dim'},
    {'from': '-NPTH.drl',           'to': '-NPTH.drl.mill'},
    {'from': '-PTH.drl',            'to': '-PTH.drl.pth'},
]

if len(gerbers) == 0:
    print "No files found with this extensions: "
    for type in gerber_types:
        print "\t" + type['from'] + ""
    print "\nEND of script."
else:
    print "Load files:"
    for g in gerbers:
        print g
    print "\n",

    print "Start renaming:"
    # Rename files depending upon their names.
    for g in gerbers:
        for t in gerber_types:
            if g.endswith(t['from']):
                # Strip the 'from' string from the old name and append the 'to' string to make the new name.
                new_g = g[:-len(t['from'])] + t['to']
                # Remove any existing file having the new name.
                print "\t" + g + " -> " + new_g
                try:
                    os.remove(new_g)
                except:
                    # An exception occurred because the file we tried to remove probably didn't exist.
                    pass
                # Rename the old file with the new name.
                os.rename(g, new_g)
                break

raw_input('Press Enter to exit.')
