#! /usr/bin/env python

srcdir = '..'
blddir = 'bin'

import sys, os
sys.path.insert(0, srcdir+"/buildtools/wafsamba")
import wafsamba, Options
import build.charset
from samba_utils import *

def set_options(opt):
    opt.BUILTIN_DEFAULT('NONE')
    opt.BUNDLED_EXTENSION_DEFAULT('s3')
    opt.RECURSE('../lib/replace')
    opt.RECURSE('build')
    opt.RECURSE('../lib/nss_wrapper')
    opt.RECURSE('../lib/socket_wrapper')
    opt.RECURSE('../lib/uid_wrapper')

    opt.add_option('--with-static-modules',
                   help=("Comma-separated list of names of modules to statically link in"),
                   action="store", dest='static_modules', default='')
    opt.add_option('--with-shared-modules',
                   help=("Comma-separated list of names of modules to build shared"),
                   action="store", dest='shared_modules', default='')


def configure(conf):
    conf.define('PACKAGE_NAME', 'Samba')
    conf.define('PACKAGE_STRING', 'Samba 3')
    conf.define('PACKAGE_TARNAME', 'samba')
    conf.define('PACKAGE_URL', '')
    conf.define('PACKAGE_VERSION', '3')
    conf.define('PACKAGE_BUGREPORT', 'samba-technical@samba.org')

    conf.DEFINE('CONFIG_H_IS_FROM_SAMBA', 1)
    conf.DEFINE('_SAMBA_BUILD_', 3, add_to_cflags=True)
    conf.DEFINE('HAVE_CONFIG_H', 1, add_to_cflags=True)
    if Options.options.developer:
        conf.ADD_CFLAGS('-DDEVELOPER -DDEBUG_PASSWORD')

    # set a limit on recursing in the waf preprocessor
    conf.env.preprocessor_recursion_limit = 10

    conf.ADD_EXTRA_INCLUDES('#source3 #source3/include #lib/replace #lib/talloc #lib/tevent #source3/libaddns #source3/librpc')

    conf.RECURSE('../lib/replace')
    conf.RECURSE('build')
    conf.RECURSE('../lib/tdb')
    conf.RECURSE('../lib/talloc')
    conf.RECURSE('../lib/tevent')
    conf.RECURSE('../lib/nss_wrapper')
    conf.RECURSE('../lib/socket_wrapper')
    conf.RECURSE('../lib/uid_wrapper')

    conf.CHECK_HEADERS('execinfo.h libexc.h libunwind.h')

    conf.CHECK_FUNCS('getcwd fchown chmod fchmod mknod mknod64')
    conf.CHECK_FUNCS('strtol strchr strupr chflags')
    conf.CHECK_FUNCS('getrlimit fsync fdatasync setpgid')
    conf.CHECK_FUNCS('setsid glob strpbrk crypt16 getauthuid')
    conf.CHECK_FUNCS('sigprocmask sigblock sigaction sigset innetgr setnetgrent getnetgrent endnetgrent')
    conf.CHECK_FUNCS('initgroups select poll rdchk getgrnam getgrent pathconf')
    conf.CHECK_FUNCS('setpriv setgidx setuidx setgroups sysconf stat64 fstat64')
    conf.CHECK_FUNCS('lstat64 fopen64 atexit grantpt lseek64 ftruncate64 posix_fallocate posix_fallocate64')
    conf.CHECK_FUNCS('fseek64 fseeko64 ftell64 ftello64 setluid')
    conf.CHECK_FUNCS('getpwnam', headers='sys/types.h pwd.h')
    conf.CHECK_FUNCS('opendir64 readdir64 seekdir64 telldir64 rewinddir64 closedir64')
    conf.CHECK_FUNCS('getpwent_r getdents64 setenv strcasecmp fcvt fcvtl')
    conf.CHECK_FUNCS('syslog vsyslog timegm setlocale nl_langinfo')
    conf.CHECK_FUNCS_IN('nanosleep', 'rt')
    conf.CHECK_FUNCS('lutimes futimes utimensat futimens')
    conf.CHECK_FUNCS('mlock munlock mlockall munlockall')
    conf.CHECK_FUNCS('memalign posix_memalign hstrerror')
    conf.CHECK_FUNCS('shmget')
    conf.CHECK_FUNCS_IN('shm_open', 'rt', checklibc=True)
    conf.CHECK_FUNCS('gettext dgettext bindtextdomain textdomain')

    # Check for inotify support
    conf.CHECK_HEADERS('linux/inotify.h asm/unistd.h sys/inotify.h')
    conf.CHECK_FUNCS('inotify_init')
    if "HAVE_LINUX_INOTIFY_H" in conf.env and "HAVE_INOTIFY_INIT" in conf.env:
        conf.DEFINE('HAVE_INOTIFY', 1)

    # Check for kernel change notify support
    conf.CHECK_CODE('''
#ifndef F_NOTIFY
#define F_NOTIFY 1026
#endif
main() {
        exit(fcntl(open("/tmp", O_RDONLY), F_NOTIFY, 0) == -1 ?  1 : 0);
}''', 'HAVE_KERNEL_CHANGE_NOTIFY', addmain=False, execute=True,
        headers='fcntl.h signal.h',
        msg="Checking for kernel change notify support")

    # Check for Linux kernel oplocks
    conf.CHECK_CODE('''
#include <sys/types.h>
#include <fcntl.h>
#include <signal.h>
#ifndef F_NOTIFY
#define F_NOTIFY 1026
#endif
main() {
        exit(fcntl(open("/tmp", O_RDONLY), F_NOTIFY, 0) == -1 ?  1 : 0);
}''', 'HAVE_KERNEL_OPLOCKS_LINUX', addmain=False, execute=True,
        msg="Checking for Linux kernel oplocks")

    # Check for IRIX kernel oplock types
    conf.CHECK_CODE('oplock_stat_t t; t.os_state = OP_REVOKE; t.os_dev = 1; t.os_ino = 1;',
                    'HAVE_KERNEL_OPLOCKS_IRIX', headers='fcntl.h',
                    msg="Checking for IRIX kernel oplock types")

    # Check for krenel share modes
    conf.CHECK_CODE('''
#include <sys/types.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/file.h>
#ifndef LOCK_MAND
#define LOCK_MAND	32
#define LOCK_READ	64
#endif
main() {
        exit(flock(open("/dev/null", O_RDWR), LOCK_MAND|LOCK_READ) != 0);
}''', 'HAVE_KERNEL_SHARE_MODES', addmain=False, execute=True,
        msg="Checking for krenel share modes")

    # Check for various members of the stat structure
    conf.CHECK_TYPES('blksize_t blkcnt_t')
    conf.CHECK_STRUCTURE_MEMBER('struct stat', 'st_blocks', define='HAVE_STAT_ST_BLOCKS',
                                headers='sys/stat.h')
    conf.CHECK_STRUCTURE_MEMBER('struct stat', 'st_blksize', define='HAVE_STAT_ST_BLKSIZE',
                                headers='sys/stat.h')

    # Check for POSIX capability support
    if "HAVE_SYS_CAPABILITY_H" in conf.env:
        conf.CHECK_FUNCS_IN('cap_get_proc', 'cap')
        conf.CHECK_CODE('''
        cap_t cap;
        cap_value_t vals[1];
        if (!(cap = cap_get_proc())) exit(1);
        vals[0] = CAP_CHOWN;
        cap_set_flag(cap, CAP_INHERITABLE, 1, vals, CAP_CLEAR);
        cap_set_proc(cap);''',
                        'HAVE_POSIX_CAPABILITIES', execute=True, lib="cap",
                        headers='sys/capability.h',
                        msg="Checking whether POSIX capabilities are available")

    # Check for int16, uint16, int32 and uint32 in rpc/types.h included from
    # rpc/rpc.h. This is *really* broken but some systems (DEC OSF1) do this.
    # -- JRA.
    if conf.CONFIG_SET("HAVE_RPC_RPC_H"):
        conf.CHECK_TYPE('int16', headers='rpc/rpc.h',
                        define='HAVE_INT16_FROM_RPC_RPC_H',
                        msg="Checking for int16 typedef included by rpc/rpc.h")
        conf.CHECK_CODE('uint16 testvar;', 'HAVE_INT16_FROM_RPC_RPC_H',
                        headers='sys/types.h rpc/rpc.h',
                        msg="Checking for uint16 typedef included by rpc/rpc.h")
        conf.CHECK_CODE('int32 testvar;', 'HAVE_INT16_FROM_RPC_RPC_H',
                        headers='sys/types.h rpc/rpc.h',
                        msg="Checking for int32 typedef included by rpc/rpc.h")
        conf.CHECK_CODE('uint32 testvar;', 'HAVE_INT16_FROM_RPC_RPC_H',
                        headers='sys/types.h rpc/rpc.h',
                        msg="Checking for uint32 typedef included by rpc/rpc.h")

    # Check if the compiler will optimize out functions
    conf.CHECK_CODE('''
if (0) {
    this_function_does_not_exist();
} else {
    return 1;
}''', 'HAVE_COMPILER_WILL_OPTIMIZE_OUT_FNS',
        msg="Checking if the compiler will optimize out functions")

    # Look for CUPS
    conf.find_program('cups-config', var='CUPS_CONFIG')
    if conf.env.CUPS_CONFIG:
        conf.check_cfg(path="cups-config", args="--cflags --ldflags --libs", package="", uselib_store="CUPS")
        conf.CHECK_HEADERS('cups/cups.h cups/language.h', lib='CUPS')

    # Check for LDAP
    conf.CHECK_HEADERS('ldap.h lber.h')
    conf.CHECK_TYPE('ber_tag_t', 'unsigned int', headers='ldap.h lber.h')

    # Check for kerberos
    conf.find_program('krb5-config', var='KRB5_CONFIG')
    if conf.env.KRB5_CONFIG:
        conf.check_cfg(path="krb5-config", args="--cflags --libs",
                       package="gssapi", uselib_store="KRB5")
        conf.CHECK_HEADERS('krb5.h krb5/locate_plugin.h', lib='KRB5')
        conf.CHECK_HEADERS('gssapi.h gssapi/gssapi_generic.h gssapi/gssapi.h com_err.h', lib='KRB5')

    conf.CHECK_FUNCS('''
_acl __acl add_proplist_entry atexit attr_getf attr_list attr_listf
attropen attr_remove attr_removef attr_set attr_setf backtrace_symbols
bindtextdomain _chdir __chdir chflags chmod _close __close _closedir
__closedir closedir64 creat64 crypt16 delproplist devnm dgettext dirfd
DNSServiceRegister _dup __dup _dup2 __dup2 endmntent endnetgrent execl
extattr_delete_fd extattr_delete_link extattr_get_fd extattr_get_file
extattr_get_link extattr_list_fd extattr_list_file extattr_list_link
extattr_set_fd extattr_set_file extattr_set_link _facl __facl _fchdir
__fchdir fchmod fchown _fcntl __fcntl fcvt fcvtl fdatasync
fdelproplist fgetea fgetproplist fgetxattr flistea flistxattr fopen64
_fork __fork fremoveea fremovexattr fseek64 fseeko64 fsetea
fsetproplist fsetxattr _fstat __fstat fstat64 _fstat64 __fstat64 fsync
ftell64 ftello64 ftruncate64 futimens futimes __fxstat getauthuid
getcwd _getcwd __getcwd getdents __getdents getdents64 getdirentries
getgrent getgrnam getgrouplist getmntent getnetgrent getpagesize
getproplist get_proplist_entry getpwanam getpwent_r getrlimit gettext
getutmpx getutxent glob grantpt hstrerror initgroups innetgr
inotify_init lgetea lgetxattr listea listxattr llistea llistxattr
llseek _llseek __llseek lremoveea lremovexattr _lseek __lseek lseek64
lsetea lsetxattr _lstat __lstat lstat64 _lstat64 __lstat64 lutimes
__lxstat memalign mknod mknod64 mlock mlockall munlock munlockall
nl_langinfo _open __open open64 _open64 __open64 _opendir __opendir
opendir64 pathconf poll posix_fallocate posix_fallocate64
posix_memalign prctl pread _pread __pread pread64 _pread64 __pread64
pututline pututxline pwrite _pwrite __pwrite pwrite64 _pwrite64
__pwrite64 rdchk _read __read _readdir __readdir readdir64 _readdir64
__readdir64 removeea removexattr rewinddir64 _seekdir __seekdir
seekdir64 select setea setenv setgidx setgroups setlocale setluid
setmntent setnetgrent setpgid setpriv setproplist setsid setuidx
setxattr shmget shm_open sigaction sigblock sigprocmask sigset
sizeof_proplist_entry _stat __stat stat64 _stat64 __stat64 statvfs
strcasecmp strchr strpbrk strsignal strtol strupr sysconf sysctlbyname
__sys_llseek syslog _telldir __telldir telldir64 textdomain timegm
updwtmp updwtmpx utimensat vsyslog _write __write __xstat
yp_get_default_domain
''')

    conf.CHECK_TYPE('struct timespec', headers='sys/time.h time.h')

    conf.CHECK_SAMBA3_CHARSET() # see build/charset.py


    default_static_modules=TO_LIST('''pdb_smbpasswd pdb_tdbsam pdb_wbc_sam rpc_lsarpc rpc_samr
                                      rpc_winreg rpc_initshutdown rpc_dssetup rpc_wkssvc rpc_svcctl
                                      rpc_ntsvcs rpc_netlogon rpc_netdfs rpc_srvsvc rpc_spoolss
                                      rpc_eventlog auth_sam auth_unix auth_winbind auth_wbc auth_server
                                      auth_domain auth_builtin auth_netlogond vfs_default
                                      nss_info_template''')

    default_shared_modules=TO_LIST('''vfs_recycle vfs_audit vfs_extd_audit vfs_full_audit vfs_netatalk
                                      vfs_fake_perms vfs_default_quota vfs_readonly vfs_cap
                                      vfs_expand_msdfs vfs_shadow_copy vfs_shadow_copy2 charset_CP850
                                      charset_CP437 auth_script vfs_readahead vfs_xattr_tdb
                                      vfs_streams_xattr vfs_streams_depot vfs_acl_xattr vfs_acl_tdb
                                      vfs_smb_traffic_analyzer vfs_preopen vfs_catia vfs_scannedonly
                                      vfs_crossrename''')

    if Options.options.developer:
        default_static_modules.extend(TO_LIST('rpc_rpcecho pdb_ads'))
        default_shared_modules.extend(TO_LIST('charset_weird perfcount_test'))

    move_to_shared = TO_LIST(Options.options.shared_modules)
    move_to_static = TO_LIST(Options.options.static_modules)

    for m in move_to_static:
        if m in default_shared_modules:
            default_shared_modules.remove(m)
            default_static_modules.append(m)
    for m in move_to_shared:
        if m in default_static_modules:
            default_static_modules.remove(m)
            default_shared_modules.append(m)

    conf.DEFINE('STRING_STATIC_MODULES', ' '.join(default_static_modules), quote=True)

    static_list = {}

    prefixes = ['vfs', 'pdb', 'rpc', 'auth', 'nss_info', 'charset', 'idmap']
    for p in prefixes:
        for m in default_static_modules:
            if m.find(p) == 0:
                if not p in static_list:
                    static_list[p] = []
                static_list[p].append(m)

    for p in prefixes:
        if p in static_list:
            conf.DEFINE('static_init_%s' % p, '{ %s_init(); }' % '_init(); '.join(static_list[p]))
        else:
            conf.DEFINE('static_init_%s' % p, '{}')

    conf.SAMBA_CONFIG_H('include/config.h')
#define static_init_idmap {  idmap_tdb_init();  idmap_passdb_init();  idmap_nss_init();}