#!/usr/bin/python
#
# losetup-stub
#
# Copyright (C) 2007, 2011  Red Hat, Inc.  All rights reserved.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

from optparse import OptionParser
import os
import sys

sys.path.append('/usr/lib/anaconda')
import isys


def usage():
    return 'Usage: %prog [-d] <loopdev> [file]'


def main(prog, args):

    def err(msg):
        sys.stderr.write('%s: %s\n' % (os.path.basename(prog), msg))
        sys.exit(1)

    parser = OptionParser(usage=usage())
    parser.add_option('-d', '--detach', action='store_true', default=False)

    opts, args = parser.parse_args(args)

    if opts.detach:
        if not args:
            err('missing operand')

        for loopdev in args:
            try:
                isys.unlosetup(loopdev)
            except SystemError as e:
                err(e)

    else:
        try:
            loopdev, image = args
        except ValueError:
            if len(args) > 2:
                err("extra operand '%s'" % args[2])
            else:
                err('missing operand')
        else:
            try:
                isys.losetup(loopdev, image)
            except SystemError as e:
                err(e)


if __name__ == '__main__':
    main(prog=sys.argv[0], args=sys.argv[1:])
