# -*- Mode: Python -*-

# Import/Archive video from a Canon HF10 (or HF100 probably) via an SDHC card reader.
#
# iMovie has a nasty habit of wanting to transcode AVCHD to the AIC codec (usually
#  with a suggestion to downsample it!).
#
# It stores the video into a subdirectory named by year, and each file
#  is renamed with a timestamp.  Also, the date on each file is preserved.
#
# It might be nice to eventually figure out how to the pull the date out
#  of the stream file.
#
# This should probably work for other AVCHD cameras, you may need to remove
# the '/PRIVATE' subdirectory.

import os
import time

# change the following depending on your camera and card
data_dirs = ['AVC_CARD/PRIVATE', 'CANON']
# change the following depending on where you want the files stored
dest_dir = '/Volumes/Drobo2/avc'

def make_dir_for_date (path):
    ctime = time.localtime (os.stat (path).st_ctime)
    year = ctime[0]
    year_path = '%s/%d' % (dest_dir, year)
    if not os.path.isdir (year_path):
        os.mkdir (year_path)
        print 'created ', year_path
    month = ctime[1]
    month_path = '%s/%d' % (year_path, month)
    if not os.path.isdir (month_path):
        os.mkdir (month_path)
        print 'created ', month_path
    dest_path = '%4d-%02d-%02d_%02d_%02d_%02d.mts' % ctime[:6]
    return '%s/%s' % (month_path, dest_path)

to_delete = []

for d in data_dirs:
    path = '/Volumes/' + d
    if os.path.isdir (path):
        path2 = path + '/AVCHD/BDMV/STREAM'
        if os.path.isdir (path2):
            files = os.listdir (path2)
            for file in files:
                path = '%s/%s' % (path2, file)
                dest = make_dir_for_date (path)
                print 'cp -p %s %s' % (path, dest)
                if not os.path.isfile (dest):
                    os.system ('cp -p %s %s' % (path, dest))
                else:
                    print 'skipping already-copied file %s' % dest
                to_delete.append (path)

if to_delete:
    print 'everything seems to have worked.  delete originals?'
    yn = raw_input()
    if yn and yn[0] in 'Yy':
        for file in to_delete:
            os.unlink (file)
else:
    print 'nothing copied, nothing to delete'
