#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006, TUBITAK/UEKAE
#
# 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; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.

import sys
import os
import shutil
import tempfile
from zipfile import BadZipfile

import pisi
from pisi.archive import ArchiveZip, ArchiveTar
import pisi.util as util

def usage(errmsg):
    print """
    Error: %s

    Usage:
      unpisi PiSi_package.pisi
    """ % (errmsg)

    sys.exit(1)

def main():

    if len(sys.argv) < 2:
        usage("PiSi package required..")

    elif not os.path.exists(sys.argv[1]):
        usage("File %s not found" % sys.argv[1])

    try:
        arc = ArchiveZip(sys.argv[1], 'zip', 'r')
    except BadZipfile, e:
        print e
        sys.exit(1)

    # Create a temporary directory in /tmp
    tempdir = tempfile.mkdtemp(prefix='unpisi')

    arc.unpack_files(['files.xml', 'metadata.xml'], '.')
    arc.unpack_files("install.tar.lzma", tempdir)
    arc.unpack_dir('comar', '.')

    tar_file = util.join_path(tempdir, "install.tar.lzma")
    if os.path.exists(tar_file):
        tar = ArchiveTar(tar_file, 'tarlzma')
        tar.unpack_dir('.')
        os.unlink(tar_file)

    shutil.rmtree(tempdir)
    return 0

if __name__ == "__main__":
    sys.exit(main())
