#!/usr/bin/python
import os, sys

def getDateTime(imPath):## output sample: '2005:01:01_12:02:16'
  if not os.path.exists(imPath):
    print 'Error: Image file \''+imPath+'\' dose not exit!'
    sys.exit(1)
  if os.path.isdir(imPath):
    print 'Error: \''+imPath+'\' is a directory!'
    sys.exit(1)
  try:
    exif = os.popen('/usr/bin/exif \''+imPath+'\'').read()
  except:
    print 'Error: Command \'exif\' is not installed. Install it then run this script.'
    sys.exit(1)
  for line in exif.split('\n'):
    if len(line)>13:
      if line[:13]=='Date and Time':
        dt=line.split('|')[1]
        dtl=len(dt)
        for i in range(dtl-1):
          if not dt[dtl-i-1] in (' ',chr(32)):
            break
        return dt[:dtl-i].replace(' ','_')
  return ''

if __name__=='__main__':
  if len(sys.argv)<2:
    print 'What to do?'
    sys.exit(1)
  fileList=[]
  for arg in sys.argv[1:]:
    if not os.path.exists(arg):
      print 'Error: \''+arg+'\': no such file or directory!'
    if arg[-1]=='/':
      argNS=arg[:-1]
    else:
      argNS=arg
    try:
      fileList += [argNS+'/'+f for f in os.listdir(argNS)]
    except:
      fileList += argNS
  for name in fileList:
    dateTime=getDateTime(name)
    if dateTime!='':
      newName=os.path.dirname(name)+'/'+dateTime+os.path.splitext(name)[-1]
      os.rename(name, newName)
      #print newName

