from waftools.plugin import plugin

def getlfsflags():
    import os
    # ask python for lfs flags, this fails on Windows and Mac OS
    # windows needs some special care, and Mac OS X alwas uses 64 bit for
    # off_t so we shouldn't be here anyway
    try:
        lfsflags = os.confstr (os.confstr_names['CS_LFS_CFLAGS']).split () 
    # If os.confstr of 'CS_LFS_CFLAGS' is not supported, try with some
    # default values
    except KeyError:
        # Mac OS X and probably other unices end here
        lfsflags = ['-D_LARGEFILE_SOURCE', '-D_FILE_OFFSET_BITS=64']
    except AttributeError:
        # Windows ends up here
        lfsflags = ['-D_LARGEFILE_SOURCE', '-D_FILE_OFFSET_BITS=64']

    return lfsflags

def plugin_configure(conf):
    # Minimum libmpg123 version for xmms2 is 1.5.1 ... versions up to 1.10.1 can use 32 and 64 bit offsets.
    # Beginning with 1.11.0, libmpg123 will always use the default file offset width,
    # while on platforms that have optional large file support there can be libmpg123_64 using 64 bits offset.
    if conf.check_cfg(package="libmpg123_64", atleast_version="1.11.0", uselib_store="mpg123", args="--cflags --libs"):
        # When we got libmpg123_64, it is reasonable to assume that lfsflags will work out.
        conf.env['CCFLAGS_mpg123'] += getlfsflags()
        return True
    else:
        # Any other libmpg123 >= 1.11.0 is guaranteed to work with default off_t.
        if conf.check_cfg(package="libmpg123", atleast_version="1.11.0", uselib_store="mpg123", args="--cflags --libs"):
            return True
        else:
            # Legacy mpg123 versions can be either large or small file-ish.
            # One could delete that branch after some time ... when deciding that mpg123 1.11.0 is widespread enough.
            if not conf.check_cfg(package="libmpg123", atleast_version="1.5.1", uselib_store="mpg123", args="--cflags --libs"):
                 return False

            # A little pitfall: mpg123 1.10.1 will always succeed the simple header check,
            # even if the size of off_t does not match the installed lib.
            # We'd need a real test program linking to the lib, calling mpg123_open(NULL, "blabla"), for example.
            if not conf.check_cc(header_name='mpg123.h', uselib='mpg123',
                         errmsg='failed',
                         msg='Testing mpg123 with default off_t'):
                lfsflags = getlfsflags()
                if not conf.check_cc(header_name='mpg123.h', uselib='mpg123',
                             cflags=lfsflags, errmsg='failed',
                             msg='Testing mpg123 with large off_t'):
                    return False
            
                conf.env['CCFLAGS_mpg123'] += lfsflags

    return True


configure, build = plugin("mpg123", configure=plugin_configure,
                          source=["mpg123.c", "id3v1.c"], libs=["mpg123"])

