#!/usr/bin/env python
"""A very simple script to set FSTYPE info field on a file.

Usage: ./set_c.py [-h] [-t '????'] [-T 1061109567] FILE [...]

Sets the FSTypeCode of the given file(s) to the specified code -
'OggS' by default.

(This script requires Mac-platform python modules.)
"""
__author__ = "Arek Korbik <arkadini@gmail.com>"
__revision__ = "0.0.1"

from Carbon import File, Files
import struct

def set_file_type_and_creator(fn, type_id = None, creator_id = None):
    fl, is_dir = File.FSPathMakeRef(fn)
    if is_dir:
        return
    ci, _fn, fsspc, pfl = fl.FSGetCatalogInfo(Files.kFSCatInfoFinderInfo)

    finfo = fsspc.FSpGetFInfo()
    if type_id is not None:
        finfo.Type = struct.pack('L', type_id)

    if creator_id is not None:
        finfo.Creator = struct.pack('L', creator_id)

    fsspc.FSpSetFInfo(finfo)


if __name__ == '__main__':
    import sys
    from optparse import OptionParser
    parser = OptionParser(usage='%prog [options] FILE [FILE ...]')

    parser.add_option('-t', '--type', dest='set_type', metavar='FSTYPE',
                      default='OggS',
                      help="Desired fstype id, 4-char string. Default: 'OggS'.")
    parser.add_option('-T', '--type_num', dest='set_type_id', metavar='FSTYPE',
                      default=None, type='int',
                      help="Desired fstype id as a long int.")

    options, args = parser.parse_args()

    if len(args) < 1:
        parser.error("No filenames specified. Try '-h' switch.")

    set_type_id = 0x4f676753  # 'OggS' = 1332176723

    if options.set_type_id is not None:
        set_type_id = options.set_type_id
    else:
        if len(options.set_type) != 4:
            parser.error("Symbolic FSTYPE must be a string 4 characters long." +
                         " (Pad with spaces if necessary).")
        else:
            set_type_id = struct.unpack('L', options.set_type)[0]

    for sfn in args:
        set_file_type_and_creator(sfn, set_type_id)
