#!/usr/bin/python
#
# Copyright (C) 2012 Luca Falavigna
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

import argparse
import magic
from os.path import exists

from XTree import Dir
from XTree import Tar
from XTree import Zip


mimetypes = {'inode/directory': 'dir',
             'application/x-gzip': 'tar',
             'application/x-bzip2': 'tar',
             'application/zip': 'zip'}

parser = argparse.ArgumentParser(description='Flatten directory contents')
parser.add_argument('archive', type=str, nargs=1,
                    help='Name of the archive or directory')
parser.add_argument('--separator', metavar='[|]', type=str, nargs=1,
                    help='Specify which directory separator to use')
parser.add_argument('--no-separator', action='store_true',
                    help='Do not use directory separators')
parser.add_argument('--purge', action='store_true',
                    help='Purge created elements on exit')
group = parser.add_mutually_exclusive_group()
group.add_argument('--directory', action='store_true',
                    help='Selected archive is a directory')
group.add_argument('--tarball', action='store_true',
                    help='Selected archive is a tarball')
group.add_argument('--zipfile', action='store_true',
                    help='Selected archive is a zipfile')
args = parser.parse_args()

if args.no_separator:
    separator = None
elif args.separator:
    separator = args.separator
else:
    separator = '|'

if exists(args.archive[0]):
    if args.tarball:
        Tar.Tar(args.archive[0], separator, args.purge)
    elif args.zipfile:
        Zip.Zip(args.archive[0], separator, args.purge)
    elif args.directory:
        Dir.Dir(args.archive[0], separator, args.purge)
    else:
        m = magic.open(magic.MAGIC_MIME)
        m.load()
        mimetype = m.file(args.archive[0]).split(';')[0]
        if mimetype in mimetypes:
            if mimetypes[mimetype] == 'tar':
                Tar.Tar(args.archive[0], separator, args.purge)
            elif mimetypes[mimetype] == 'zip':
                Zip.Zip(args.archive[0], separator, args.purge)
            elif mimetypes[mimetype] == 'dir':
                Dir.Dir(args.archive[0], separator, args.purge)
        else:
            print 'Unsupported file type'
else:
    print '%s does not exist' % args.archive[0]

