#!/usr/bin/python
#
# mknod-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 stat
import sys


def usage():
    return 'Usage: %prog <path> [b|c] <major> <minor>'


def main(prog, args):

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

    DEVTYPES = { 'b' : stat.S_IFBLK,
                 'c' : stat.S_IFCHR }

    DEVMODE = 0644

    parser = OptionParser(usage=usage())
    opts, args = parser.parse_args(args)

    try:
        path, devtype, major, minor = args
    except ValueError:
        if len(args) > 4:
            err("extra operand '%s'" % args[4])
        else:
            err('missing operand')

    try:
        devtype = DEVTYPES[devtype]
    except KeyError:
        err("invalid device type '%s'" % devtype)

    try:
        major = int(major)
    except ValueError:
        err("invalid major device number '%s'" % major)

    try:
        minor = int(minor)
    except ValueError:
        err("invalid minor device number '%s'" % minor)

    try:
        os.mknod(path, DEVMODE | devtype, os.makedev(major, minor))
    except OSError as e:
        err(e)


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