"""
  convert data file (disk image) to macbinary setting type and creator.

  from: https://gist.github.com/depp/5d351a871078213b6a9188e27bbf3b4d
  rsrc2macbinary.py - convert resource fork to MacBinary file
  altered to convert data fork instead.
"""
import datetime
import os
import struct
import sys
import zlib

def die(*msg):
    print('Error:', *msg, file=sys.stderr)
    raise SystemExit(1)

EPOCH = datetime.datetime(1904, 1, 1)

def main(argv):
    if len(argv) != 2:
        die('usage: python convert_to_macbinary.py  ')
    inpath, outpath = argv
    st = os.stat(inpath)
    mtime = datetime.datetime.utcfromtimestamp(st.st_mtime)
    mtime_num = int((mtime - EPOCH).total_seconds())
    with open(inpath, 'rb') as fp:
        data = fp.read()
    name = os.path.splitext(os.path.basename(outpath))[0]
    if name.endswith(".diskcopy"):
        name = name[:-len(".diskcopy")] + ".img"
    header = struct.pack(
        '>B64p4s4sBBhhhBBIIIIhB14sIhBB',
        0, # old version number
        name.encode('ASCII'), # name
        b'dImg', # file type
        b'dCpy', # file creator
        0, # finder flags
        0, # zero fill
        0, 0, # position in finder window
        0, # window or folder ID
        0, # protected
        0, # zero fill
        len(data), # data fork length
        0, # rsrc fork length
        mtime_num, # creation date
        mtime_num, # last modified
        0, # get info comment length
        0, # finder flags
        b'', # padding
        0, # unpacked length
        0, # secondary header length
        129, # version of MacBinary used to create
        129, # version of MacBinary needed to extract
    )
    with open(outpath, 'wb') as fp:
        fp.write(header)
        fp.write(struct.pack('>I', zlib.crc32(header)))
        fp.write(data)
        fp.write(b'\x00' * ((-len(data)) & 127))

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