#!/usr/bin/python -tt
# vim: ai ts=4 sts=4 et sw=4

#    Copyright (c) 2009 Intel Corporation
#
#    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 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,sys
import optparse

from spectacle import specify
from spectacle import logger

MF_TEMPLATE = """PKG_NAME := %s
SPECFILE = $(addsuffix .spec, $(PKG_NAME))
YAMLFILE = $(addsuffix .yaml, $(PKG_NAME))


include /usr/share/packaging-tools/Makefile.common
"""

def parse_options(args):
    import spectacle.__version__

    usage = "Usage: %prog [options] [yaml-path]"
    parser = optparse.OptionParser(usage, version=spectacle.__version__.VERSION)

    parser.add_option("-o", "--output", type="string",
                      dest="outfile_path", default=None,
                      help="Path of output spec file")
    parser.add_option("-s", "--skip-scm", action="store_true",
                      dest="skip_scm", default=False,
                      help="Skip to check upstream SCM when specified in YAML")
    parser.add_option("-N", "--not-download", action="store_true",
                      dest="not_download", default=False,
                      help="Do not try to download newer source files")
    parser.add_option("-n", "--non-interactive", action="store_true",
                      dest="noninteractive", default=False,
                      help="Non interactive running, to use default answers")

    return parser.parse_args()

if __name__ == '__main__':
    """ Main Function """

    (options, args) = parse_options(sys.argv[1:])

    if not args:
        # no YAML-path specified, search in CWD
        import glob
        yamlls = glob.glob('*.yaml')
        if not yamlls:
            logger.error('Cannot find valid spectacle file(*.yaml) in current directory, please specify one.')
        elif len(yamlls) > 1:
            logger.error('Find multiple spectacle files(*.yaml) in current directory, please specify one.')

        yaml_fpath = yamlls[0]
    else:
        yaml_fpath = args[0]

    if options.noninteractive:
        logger.set_mode(False)

    # check if the input file exists
    if not os.path.exists(yaml_fpath):
        # input file does not exist
        logger.error("%s: File does not exist" % yaml_fpath)

    if options.outfile_path:
        if os.path.sep in options.outfile_path:
            out_fpath = os.path.abspath(options.outfile_path)
        else:
            out_fpath = options.outfile_path
    else:
        # %{name}.spec as the default if not specified
        out_fpath = None

    # check the working path
    if yaml_fpath.find(os.path.sep) != -1 and os.path.dirname(yaml_fpath) != os.path.curdir:
        wdir = os.path.dirname(yaml_fpath)
        logger.info('Changing to working dir: %s' % wdir)
        os.chdir(wdir)

    yaml_fname = os.path.basename(yaml_fpath)

    # check Makefile from packaging-tools
    if not os.path.exists('Makefile'):
        logger.warning('There is no "Makefile" for this package, please update it using packaging-tools')
        answer = logger.ask('Need to create Makefile from default template?', False)
        if answer:
            mf = open('Makefile', 'w')
            mf.write(MF_TEMPLATE % os.path.basename(yaml_fname).rstrip('.yaml'))
            mf.close()

    spec_fpath, newspec = specify.generate_rpm(yaml_fname, spec_fpath=out_fpath, download_new=not options.not_download, skip_scm=options.skip_scm)
    if newspec:
        logger.warning("NEW spec file created: %s, maybe customized spec content is needed!" % spec_fpath)
    else:
        logger.info("Old spec file exists, patching %s ..." % spec_fpath)
