#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Copy files from a source directory to a target directory starting at some point.

The motivating purpose for this was that Beatrice wanted to copy
photos off her SD card onto her computer, but her computer had no SD
card reader. So I was copying them onto a USB pen drive that didn’t
have enough space.  This program copies until it runs out of space,
spitting out lines that explain how to restart from the checkpoint.

"""
import os, shutil, sys

def main(whence, whereto):
    whencedir, whencefile = os.path.split(whence)

    filenames = os.listdir(whencedir)
    filenames.sort()

    for filename in filenames:
        if filename >= whencefile:
            pathname = os.path.join(whencedir, filename)
            print repr(sys.argv[0]), repr(pathname), repr(whereto), "# to restart"

            try:
                shutil.copy2(pathname, whereto)
            except:
                # copy2 doesn't delete partially-copied files :(
                destfile = os.path.join(whereto, filename)
                if os.path.exists(destfile):
                    os.unlink(destfile)
                raise

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])
