#!/usr/bin/env python
# Copyright (C) 2014 Colin Walters <walters@verbum.org>, Andy Grimm <agrimm@redhat.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import os
import sys

from rpmostreecompose import imagefactory, installer, treecompose
from rpmostreecompose import taskrunner, version, liveimage

def execgjs(cmd, argv):
    jsdir=os.path.join(os.environ['OSTBUILD_DATADIR'] + '/js')
    target_argv = ['gjs', '-I', jsdir, jsdir + '/main.js', cmd]
    target_argv.extend(argv)
    os.execvp('gjs', target_argv)

def usage(iserr):
    stream = sys.stderr if iserr else sys.stdout
    stream.write("""Builtins:
  treecompose - Use rpm-ostree to compose RPMs to a tree
  imagefactory - Use ImageFactory to create a disk image
  installer - Use Lorax to create an installable ISO and PXE boot loader
  liveimage - Use Imagefactory and Live Media Creator to create live media
  create-vm-disk - Deprecated in favor of imagefactory
  postprocess-disk - Deprecated; instead use imagefactory to generate multiple images
""")
    sys.exit(1 if iserr else 0)

def main():
    if len(sys.argv) <= 1:
        usage(False)
    if os.getuid() != 0:
        print "\nrpm-ostee-toolbox requires you to run as root"
        sys.exit(1)
    if str(sys.argv[1]).lower() == '-h' or str(sys.argv[1]).lower() == '--help':
        usage(False)
    if str(sys.argv[1]).lower() == '-v' or str(sys.argv[1]).lower() == '--version':
        print 'rpm-ostree-toolbox %s' % (version.version)
        sys.exit(0)
    cmd = sys.argv.pop(1)
    if cmd == 'imagefactory':
        imagefactory.main(cmd)
    elif cmd == 'installer':
        installer.main(cmd)
    elif cmd == 'treecompose':
        treecompose.main(cmd)
    elif cmd == 'liveimage':
        liveimage.main(cmd)
    elif cmd == 'taskrunner':
        taskrunner.main()
    elif cmd in ['create-vm-disk', 'postprocess-disk', 'trivial-autocompose']:
        execgjs(cmd, sys.argv[1:])
    else:
        sys.stderr.write("""Unknown argument: %s\n""" % (cmd, ))
        usage(True)

if __name__ == '__main__':
    main()
    pass
