#!/usr/bin/python -tt
# dvdtar - packs the contents of a DVD video into a tar file
# Copyright (C) 2005  Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# 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.
#
# 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.
#
# Get the latest version at: http://www.dlitz.net/software/dvd2tar/
#

version = "0.1"

import sys
import os
import tarfile

try:
    import subprocess
except ImportError:
    if sys.hexversion <= 0x2040000:
        print >>sys.stderr, \
"""
* You need the subprocess module, which ships with Python 2.4, and is
* available as an add-on for earlier versions of Python.  Note that if you
* already have Python 2.4 installed, you may be able to modify the first line
* of this script to use it (ie. change /usr/bin/python to /usr/bin/python2.4).
"""
    raise


if len(sys.argv[1:]) != 1:
    print >>sys.stderr, "dvd2tar v%s - packs the contents of a DVD video into a tar file" % version
    print >>sys.stderr, "Usage: %s /path/to/mounted/dvd > output.tar" % sys.argv[0]
    sys.exit(1)

inputDir = sys.argv[1]

vtsdir = [d for d in os.listdir(inputDir) if d.lower() == 'video_ts'][0]

tar = tarfile.open(fileobj=sys.stdout, mode='w|')

info = tar.gettarinfo(os.path.join(inputDir, vtsdir))
info.name = vtsdir.upper()
tar.addfile(info)

# subprocess stderr file object
#sp_stderr = open("/dev/null", "wb")
sp_stderr = sys.stderr

for file in os.listdir(os.path.join(inputDir, vtsdir)):
    args = ["vobcopy", "-i", inputDir, "-O", os.path.join(file), "-o", "-"]
    p = subprocess.Popen(args=args, stdout=subprocess.PIPE, stderr=sp_stderr)

    info = tar.gettarinfo(os.path.join(inputDir, vtsdir, file))
    info.name = os.path.join(vtsdir, file).upper()
    tar.addfile(info, p.stdout)
    
    rc = p.wait()
    if rc != 0:
        raise RuntimeError, "vobcopy failed with return code %r" % (rc,)

tar.close()


# vim:set ts=4 sw=4 sts=4 expandtab:
