#!/opt/local/bin/python
"""usage: %(prog)s image src dst

Copy src from a disk image image into dst. Check CpMac manual for the
semantics of src and dst.

Using disk image you can create template folders and files with custom
icon and other mac specific meta data, while using version control
system that does not support Mac specific meta data.

Requires that the developer tools are installed in the default location.

@copyright: (c) 2006 Nir Soffer <nirs@freeshell.org>
@license: GNU GPL, see COPYING
"""

import sys, os, commands, plistlib


def fail(msg, error=1):
    sys.stderr.write(msg + '\n')
    sys.exit(error)
    

def usage():
    return __doc__ % {'prog': os.path.basename(sys.argv[0])}


def run(command):
    """ Run command and return the output, exit on errors """
    error, output = commands.getstatusoutput(command)
    if error:
        fail('error: %s failed: %s' % (command, output))
    return output


def copyFromImage(image, src, dst):
    """ Copy src from a disk image into dst """
    output = run('hdiutil attach %s -plist -readonly -private -nobrowse'
                 % image)
    try:
        info = plistlib.readPlistFromString(output)
        for entity in info['system-entities']:
            if 'mount-point' in entity:
                mountPoint = entity['mount-point']
                devEntry = entity['dev-entry']
                break
        else:
            fail('error: no mount point and dev entry?!')

        run('/Developer/Tools/CpMac -r -p "%s/%s" "%s"'
            % (mountPoint, src, dst))
    finally:
        run('hdiutil detach %s' % devEntry)

        
if __name__ == '__main__':
    if len(sys.argv) != 4:
        fail(usage())
    copyFromImage(*sys.argv[1:])
