import os, subprocess
import optparse

def main():
    parser = optparse.OptionParser("usage %prog "+\
      "(-f <file>) (-r <dirname>)")
    parser.add_option('-f', dest='fname', type='string', help='specify file to convert')
    parser.add_option('-r', dest='dname', type='string', help='specify the dirname where files to convert')
    (options, args) = parser.parse_args()
    if options.fname != None and options.dname == None:
    	filename = options.fname
    	convert(filename)
    elif options.fname == None and options.dname != None:
    	dirname = options.dname
    	for i in os.listdir(dirname):
    		if os.path.isfile(os.path.join(dirname,i)) and i[-3:] =='crt':
    			convert(dirname+i)
    else:
    	print parser.usage

def convert(filecrt):
	fil = open(filecrt,'r')
	if fil.readline() != '-----BEGIN CERTIFICATE-----\n':
		filepem = filecrt.replace('crt','pem')
		cmdstr = ["openssl", "x509","-inform","DES","-in", filecrt,"-out",filepem]
		process = subprocess.Popen(cmdstr,stdin=None)

        fil.close()

if __name__ == '__main__':
	main()