#!/usr/bin/python -t
#
# mic-create-bootstrap : create a bootstrap to run mic-image-creator
#
# Copyright 2009, Intel Inc.
#
# 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; version 2 of the License.
#
# 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

import os
import os.path
import sys
import optparse
import shutil
import subprocess
import signal
import tempfile
from mic.imgcreate.fs import *
from mic.imgcreate.bootstrap import *

try:
    import mic.__version__
    version = mic.__version__.version
except:
    version = 'unknown'

class Usage(Exception):
    def __init__(self, msg = None, no_error = False):
        Exception.__init__(self, msg, no_error)

def parse_options(args):
    parser = optparse.OptionParser(
        usage="mic-create-bootstrap [options]"
        , version = version)

    parser.add_option("-k", "--cache", type="string", dest="cachedir",
                    help="Repo cache dir, it saves too much time to use repo cache.")
    parser.add_option("-n", "--reponame", type="string",
                      dest="reponame",
                      help="repo name, get repo cache according to this"
                     )
    parser.add_option("-r", "--repourl", type="string", dest="repourl",
                      help="Repo URL"
                     )
    parser.add_option("-p", "--proxy", type="string", dest="proxy",
                      help="Specify a http proxy if needed"
                     )
    parser.add_option("-o", "--outdir", type="string",
                      dest="outdir",
                      help="Output directory to use, it should be empty if existed "
                     )

    (options, args) = parser.parse_args()

    return options

def main():
    try:
        options = parse_options(sys.argv[1:])
        if not options:
            return 2
    except Usage, (msg, no_error):
        if no_error:
            out = sys.stdout
            ret = 0
        else:
            out = sys.stderr
            ret = 2
        if msg:
            print >> out, msg
        return ret

    if os.geteuid () != 0:
        print "You must run mic-create-bootstrap as root"
        return 1

    if not options.reponame:
        raise Usage("Please specify repo name, it can help reduce runtime if it has been cached.")

    if not options.outdir:
       raise Usage("Please use -o or --outdir option to specify target bootstrap directory.")
    elif not os.path.exists(options.outdir):
       try:
           os.makedirs(options.outdir)
       except OSError, (err, msg):
           raise Usage(msg)
    elif os.path.isdir(options.outdir) and len(os.listdir(options.outdir)) != 0:
       raise Usage("Output dir must be empty or non-existed directory.")
    elif not os.path.isdir(options.outdir):
       raise Usage("Output dir must be empty or non-existed directory.")

    proxies = {}
    if options.proxy:
        proxies = {"http":options.proxy,"https":options.proxy, "ftp":options.proxy, "ftps":options.proxy}

    rmcachedir = False
    if not options.cachedir:
        try:
            options.cachedir = tempfile.mkdtemp(dir = "/var/tmp", prefix = "bootstrapcache-")
            rmcachedir = True
        except OSError, (err, msg):
            raise Usage("Failed to create bootstrap cache directory on %s: %s" % ("/var/tmp", msg))

    get_repo_metadata(options.repourl, options.cachedir, options.reponame, proxies)
    build_bootstrap(options.repourl, options.cachedir, options.reponame, options.outdir, proxies)
    if rmcachedir:
        shutil.rmtree(options.cachedir, ignore_errors = True)
    print "Finished."
    return 0

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