import os
from Params import pprint
import Params
import Common

def build(bld):
    env = bld.env()

    obj = bld.create_obj('cc', 'rubyext', 'rubyext')
    obj.target = 'xmmsclient_ext'
    obj.includes = '../../../include ../../../includepriv'
    obj.source = "rb_xmmsclient_main.c rb_xmmsclient.c rb_playlist.c rb_collection.c rb_result.c".split()
    obj.uselib_local = 'xmmsclient'
    obj.install_var = "ARCHDIR_ruby"

    Common.install_files('LIBDIR_ruby', '.', 'xmmsclient.rb')
    Common.install_files('LIBDIR_ruby', 'xmmsclient', 'sync.rb')
    Common.install_files('LIBDIR_ruby', 'xmmsclient', 'async.rb')

    # glib
    obj = bld.create_obj('cc', 'rubyext', 'rubyext')
    obj.target = 'xmmsclient_glib'
    obj.includes = '../../../include ../../../includepriv'
    obj.source = ['rb_xmmsclient_glib.c']
    obj.uselib_local = 'xmmsclient-glib xmmsclient'
    obj.uselib = 'glib2'
    obj.install_var = "ARCHDIR_ruby"
    obj.env["shlib_PREFIX"] = ''

    # ecore
    if 'src/clients/lib/xmmsclient-ecore' in env['XMMS_OPTIONAL_BUILD']:
        obj = bld.create_obj('cc', 'rubyext', 'rubyext')
        obj.target = 'xmmsclient_ecore'
        obj.includes = '../../../include ../../../includepriv'
        obj.source = ['rb_xmmsclient_ecore.c']
        obj.uselib_local = 'xmmsclient-ecore xmmsclient'
        obj.uselib = 'ecore'
        obj.install_var = "ARCHDIR_ruby"
        obj.env["shlib_PREFIX"] = ''

def configure(conf):
    if Params.g_options.rubybinary:
        ruby = Params.g_options.rubybinary
    else:
        ruby = conf.find_program('ruby', var='RUBY')

    if not ruby:
        return False

    version_str = os.popen(ruby + " -e 'puts defined?(VERSION) ? VERSION : RUBY_VERSION'").read().strip()
    if version_str:
        version = [int(a) for a in version_str.split('.')][:2]
    if not version_str or version < [1, 8]:
        conf.check_message('ruby version', '> 1.8', False, version_str or 'not found')
        return False
    conf.check_message('ruby version', '> 1.8', True, version_str)

    if version == [1, 8]: # Ruby 1.8
        ruby_h = os.popen(ruby + " -rrbconfig -e 'puts File.exist?(Config::CONFIG[\"archdir\"] + \"/ruby.h\")'").read().strip()
    else: # Ruby 1.9
        ruby_h = os.popen(ruby + " -rrbconfig -e 'puts File.exist?(Config::CONFIG[\"rubyhdrdir\"] + \"/ruby.h\")'").read().strip()
    if ruby_h != 'true':
        conf.check_message('ruby', 'header file', False)
        return False
    conf.check_message('ruby', 'header file', True)

    dir = os.popen(ruby + " -rrbconfig -e 'puts \"%s\" % [].fill(Config::CONFIG[\"archdir\"], 0..1)'").read().strip()
    conf.env["CPPPATH_ruby"] = [dir]
    conf.env["LINKFLAGS_ruby"] = '-L%s' % dir

    if version == [1, 9]: # Ruby 1.9
        hdir = os.popen(ruby + " -rrbconfig -e 'puts Config::CONFIG[\"rubyhdrdir\"]'").read().strip()
        conf.env["CPPPATH_ruby"] += [hdir, os.path.join(hdir, "ruby")]
        hdir = os.popen(ruby + " -rrbconfig -e 'puts File.join(Config::CONFIG[\"rubyhdrdir\"], Config::CONFIG[\"arch\"])'").read().strip()
        conf.env["CPPPATH_ruby"] += [hdir]

    lib = os.popen(ruby + " -rrbconfig -e 'print Config::CONFIG[\"RUBY_SO_NAME\"]'").read().strip()

    # Check for rb_protect_inspect for our inspect methods.
    test = conf.create(enumerator='function')
    test.function = 'rb_protect_inspect'
    test.headers = ['ruby.h']
    test.include_paths = conf.env["CPPPATH_ruby"]
    test.libs = [lib]
    test.mandatory = 0
    if test.run():
        conf.env['CCDEFINES_ruby'] = ['HAVE_PROTECT_INSPECT']

    ldflags = os.popen(ruby + " -rrbconfig -e 'print Config::CONFIG[\"LDSHARED\"]'").read().strip()
    # ok this is really stupid, but the command and flags are combined.
    # so we try to find the first argument...
    flags = ldflags.split()
    while flags and flags[0][0] != '-':
        flags = flags[1:]
    conf.env["LINKFLAGS_ruby"] += " "+" ".join(flags)

    ldflags = os.popen(ruby + " -rrbconfig -e 'print Config::CONFIG[\"LIBS\"]'").read().strip()
    conf.env["LINKFLAGS_ruby"] += " "+ldflags
    ldflags = os.popen(ruby + " -rrbconfig -e 'print Config::CONFIG[\"LIBRUBYARG_SHARED\"]'").read().strip()
    conf.env["LINKFLAGS_ruby"] += " "+ldflags

    cflags = os.popen(ruby + " -rrbconfig -e 'print Config::CONFIG[\"CCDLFLAGS\"]'").read().strip()
    conf.env["CCFLAGS_ruby"] = cflags

    if not Params.g_options.rubyarchdir:
        conf.env["ARCHDIR_ruby"] = os.popen(ruby + " -rrbconfig -e 'print Config::CONFIG[\"sitearchdir\"]'").read().strip()
    else:
        conf.env["ARCHDIR_ruby"] = Params.g_options.rubyarchdir

    if not Params.g_options.rubylibdir:
        conf.env["LIBDIR_ruby"] = os.popen(ruby + " -rrbconfig -e 'print Config::CONFIG[\"sitelibdir\"]'").read().strip()
    else:
        conf.env["LIBDIR_ruby"] = Params.g_options.rubylibdir

    if not os.path.commonprefix([conf.env['ARCHDIR_ruby'], conf.env['PREFIX']]).startswith(conf.env['PREFIX']):
        Params.warning('default ruby archdir is not under PREFIX. specify path '
                + 'manually using --with-ruby-archdir if you don\'t want the '
                + 'ruby bindings to be installed to ' + conf.env['ARCHDIR_ruby'])

    if not os.path.commonprefix([conf.env['LIBDIR_ruby'], conf.env['PREFIX']]).startswith(conf.env['PREFIX']):
        Params.warning('default ruby libdir is not under PREFIX. specify path '
                + 'manually using --with-ruby-libdir if you don\'t want the '
                + 'ruby bindings to be installed to ' + conf.env['LIBDIR_ruby'])

    conf.env["rubyext_PREFIX"] = ''
    conf.env["rubyext_SUFFIX"] = '.' + os.popen(ruby + " -rrbconfig -e 'print Config::CONFIG[\"DLEXT\"]'").read().strip()
    conf.env["rubyext_USELIB"] = "ruby"
    conf.env["rubyext_obj_ext"] = conf.env["shlib_obj_ext"]

    return True

def set_options(opt):
    opt.add_option('--with-ruby-archdir', type="string", dest="rubyarchdir")
    opt.add_option('--with-ruby-libdir', type="string", dest="rubylibdir")
    opt.add_option('--with-ruby-binary', type='string', dest='rubybinary')
