summaryrefslogtreecommitdiff
path: root/ctdb/wscript
blob: f8259c7c1d64f2c9830b634522140fffaaa06ffe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
#!/usr/bin/env python

APPNAME = 'ctdb'

blddir = 'bin'

import sys, os

# find the buildtools directory
srcdir = '.'
while not os.path.exists(srcdir+'/buildtools') and len(srcdir.split('/')) < 5:
    srcdir = srcdir + '/..'
sys.path.insert(0, srcdir + '/buildtools/wafsamba')

import wafsamba, samba_dist, Options, Logs, Utils
import samba_utils, samba_version

env = samba_utils.LOAD_ENVIRONMENT()
if os.path.isfile('./VERSION'):
    vdir = '.'
elif os.path.isfile('../VERSION'):
    vdir = '..'
else:
    Logs.error("VERSION file not found")

version = samba_version.samba_version_file('%s/VERSION' % vdir, vdir, env)
VERSION = version.STRING.replace('-', '.')

default_prefix = Options.default_prefix = '/usr/local'

samba_dist.DIST_DIRS('''ctdb:. lib/replace:lib/replace lib/talloc:lib/talloc
                        lib/tevent:lib/tevent lib/tdb:lib/tdb
                        third_party/socket_wrapper:third_party/socket_wrapper
                        third_party/popt:third_party/popt
                        lib/util:lib/util lib/tdb_wrap:lib/tdb_wrap
                        lib/ccan:lib/ccan libcli/util:libcli/util
                        lib/async_req:lib/async_req
                        buildtools:buildtools third_party/waf:third_party/waf''')

manpages_binary = [
    'ctdb.1',
    'ctdbd.1',
    'ltdbtool.1',
    'ping_pong.1'
]

manpages_misc = [
    'ctdb_diagnostics.1',
    'ctdbd_wrapper.1',
    'onnode.1',
    'ctdbd.conf.5',
    'ctdb.7',
    'ctdb-statistics.7',
    'ctdb-tunables.7',
]

manpages_etcd = [
    'ctdb-etcd.7',
]

manpages_ceph = [
    'ctdb_mutex_ceph_rados_helper.7',
]


def set_options(opt):
    opt.PRIVATE_EXTENSION_DEFAULT('ctdb')

    opt.RECURSE('lib/replace')

    opt.RECURSE('lib/util')

    opt.RECURSE('lib/talloc')
    opt.RECURSE('lib/tevent')
    opt.RECURSE('lib/tdb')

    opt.add_option('--enable-infiniband',
                   help=("Turn on infiniband support (default=no)"),
                   action="store_true", dest='ctdb_infiniband', default=False)
    opt.add_option('--enable-pmda',
                   help=("Turn on PCP pmda support (default=no)"),
                   action="store_true", dest='ctdb_pmda', default=False)
    opt.add_option('--enable-etcd-reclock',
                   help=("Enable etcd recovery lock helper (default=no)"),
                   action="store_true", dest='ctdb_etcd_reclock', default=False)

    opt.add_option('--with-libcephfs',
                   help=("Directory under which libcephfs is installed"),
                   action="store", dest='libcephfs_dir', default=None)
    opt.add_option('--enable-ceph-reclock',
                   help=("Enable Ceph CTDB recovery lock helper (default=no)"),
                   action="store_true", dest='ctdb_ceph_reclock', default=False)

    opt.add_option('--with-logdir',
                   help=("Path to log directory"),
                   action="store", dest='ctdb_logdir', default=None)
    opt.add_option('--with-socketpath',
                   help=("path to CTDB daemon socket"),
                   action="store", dest='ctdb_sockpath', default=None)


def configure(conf):

    # No need to build python bindings for talloc/tevent/tdb
    if conf.IN_LAUNCH_DIR():
        conf.env.standalone_ctdb = True
        Options.options.disable_python = True

    conf.RECURSE('lib/replace')

    if conf.env.standalone_ctdb:
        conf.SAMBA_CHECK_PERL(mandatory=True)

        conf.SAMBA_CHECK_PYTHON(mandatory=False, version=(2,5,0))
        conf.SAMBA_CHECK_PYTHON_HEADERS(mandatory=False)

    if conf.CHECK_FOR_THIRD_PARTY():
        conf.RECURSE('third_party/popt')
        if conf.env.standalone_ctdb or conf.CONFIG_GET('ENABLE_SELFTEST'):
            conf.RECURSE('third_party/socket_wrapper')
            conf.env.SOCKET_WRAPPER_SO_PATH = conf.CONFIG_GET('LIBSOCKET_WRAPPER_SO_PATH')
    else:
        if not conf.CHECK_POPT():
            raise Utils.WafError('popt development packages have not been found\nIf third_party is installed, check that it is in the proper place.')
        else:
            conf.define('USING_SYSTEM_POPT', 1)
        conf.env.SOCKET_WRAPPER_SO_PATH = ''


        if conf.env.standalone_ctdb or conf.CONFIG_GET('ENABLE_SELFTEST'):
            if not conf.CHECK_SOCKET_WRAPPER():
                raise Utils.WafError('socket_wrapper package has not been found.\nIf third_party is installed, check that it is in the proper place.')
            else:
                conf.define('USING_SYSTEM_SOCKET_WRAPPER', 1)
                conf.env.SOCKET_WRAPPER_SO_PATH = conf.CONFIG_GET('LIBSOCKET_WRAPPER_SO_PATH')

    conf.RECURSE('lib/util')

    conf.RECURSE('lib/talloc')
    conf.RECURSE('lib/tevent')
    conf.RECURSE('lib/tdb')

    conf.CHECK_HEADERS('sched.h')
    conf.CHECK_HEADERS('procinfo.h')
    if sys.platform.startswith('aix') and not conf.CHECK_FUNCS('thread_setsched'):
        Logs.error('Need thread_setsched() on AIX')
        sys.exit(1)
    elif not conf.CHECK_FUNCS('sched_setscheduler'):
        Logs.error('Need sched_setscheduler()')
        sys.exit(1)
    conf.CHECK_FUNCS('mlockall')

    if not conf.CHECK_VARIABLE('ETIME', headers='errno.h'):
        conf.DEFINE('ETIME', 'ETIMEDOUT')

    if sys.platform.startswith('linux'):
        conf.SET_TARGET_TYPE('pcap', 'EMPTY')
    else:
        if not conf.CHECK_HEADERS('pcap.h'):
            Logs.error('Need libpcap')
            sys.exit(1)
        if not conf.CHECK_FUNCS_IN('pcap_open_live', 'pcap', headers='pcap.h'):
            Logs.error('Need libpcap')
            sys.exit(1)

    if not conf.CHECK_FUNCS_IN('backtrace backtrace_symbols', 'execinfo',
                               checklibc=True, headers='execinfo.h'):
        Logs.error('backtrace support not available')

    have_pmda = False
    if Options.options.ctdb_pmda:
        pmda_support = True

        if not conf.CHECK_HEADERS('pcp/pmapi.h pcp/impl.h pcp/pmda.h',
                                  together=True):
            pmda_support = False
        if not conf.CHECK_FUNCS_IN('pmProgname', 'pcp'):
            pmda_support = False
        if not conf.CHECK_FUNCS_IN('pmdaDaemon', 'pcp_pmda'):
            pmda_support = False
        if pmda_support:
            conf.CHECK_TYPE_IN('__pmID_int', 'pcp/pmapi.h pcp/impl.h')
            have_pmda = True
        else:
            Logs.error("PMDA support not available")
            sys.exit(1)
    if have_pmda:
        Logs.info('Building with PMDA support')
        conf.define('HAVE_PMDA', 1)
        conf.env.CTDB_PMDADIR = os.path.join(conf.env.LOCALSTATEDIR,
                                             'lib/pcp/pmdas/ctdb')

    have_infiniband = False
    if Options.options.ctdb_infiniband:
        ib_support = True

        if not conf.CHECK_HEADERS('infiniband/verbs.h rdma/rdma_cma.h'):
            ib_support = False
        if not conf.CHECK_FUNCS_IN('ibv_create_qp', 'ibverbs'):
            ib_support = False
        if not conf.CHECK_FUNCS_IN('rdma_connect', 'rdmacm'):
            ib_support = False
        if ib_support:
            have_infiniband = True
        else:
            Logs.error("Infiniband support not available")
            sys.exit(1)
    if have_infiniband:
        Logs.info('Building with Infiniband support')
        conf.define('HAVE_INFINIBAND', 1)
        conf.define('USE_INFINIBAND', 1)

    have_etcd_reclock = False
    if Options.options.ctdb_etcd_reclock:
        try:
            conf.check_python_module('etcd')
            have_etcd_reclock = True
        except:
            Logs.error('etcd support not available')
            sys.exit(1)
    if have_etcd_reclock:
        Logs.info('Building with etcd support')
    conf.env.etcd_reclock = have_etcd_reclock

    if Options.options.ctdb_ceph_reclock:
        # Use custom libcephfs library path if provided. XXX The top level build
        # explicitly sets LIBPATH_CEPH-COMMON when libcephfs_dir isn't provided.
        if Options.options.libcephfs_dir:
            conf.env['CPPPATH_RADOS'] = Options.options.libcephfs_dir + '/include'
            conf.env['LIBPATH_RADOS'] = Options.options.libcephfs_dir + '/lib'
            conf.env['LIBPATH_CEPH-COMMON'] = conf.env['LIBPATH_RADOS'] + '/ceph'

        if (conf.CHECK_HEADERS('rados/librados.h', False, False, 'rados') and
					conf.CHECK_LIB('rados', shlib=True)):
            conf.CHECK_LIB('ceph-common', shlib=True)
            Logs.info('Building with Ceph librados recovery lock support')
            conf.define('HAVE_LIBRADOS', 1)
        else:
            Logs.error("Missing librados for Ceph recovery lock support")
            sys.exit(1)

    conf.env.CTDB_BINDIR = os.path.join(conf.env.EXEC_PREFIX, 'bin')
    conf.env.CTDB_ETCDIR = os.path.join(conf.env.SYSCONFDIR, 'ctdb')
    conf.env.CTDB_VARDIR = os.path.join(conf.env.LOCALSTATEDIR, 'lib/ctdb')
    conf.env.CTDB_RUNDIR = os.path.join(conf.env.LOCALSTATEDIR, 'run/ctdb')
    conf.env.CTDB_HELPER_BINDIR = os.path.join(conf.env.LIBEXECDIR, 'ctdb')

    if Options.options.ctdb_logdir:
        conf.env.CTDB_LOGDIR = Options.options.ctdb_logdir
    else:
        conf.env.CTDB_LOGDIR = os.path.join(conf.env.LOCALSTATEDIR, 'log')

    if Options.options.ctdb_sockpath:
        conf.env.CTDB_SOCKPATH = Options.options.ctdb_sockpath
    else:
        conf.env.CTDB_SOCKPATH = os.path.join(conf.env.CTDB_RUNDIR,
                                              'ctdbd.socket')
    conf.define('CTDB_SOCKET', conf.env.CTDB_SOCKPATH)

    conf.ADD_CFLAGS('''-DCTDB_HELPER_BINDIR=\"%s\"
                       -DLOGDIR=\"%s\"
                       -DCTDB_ETCDIR=\"%s\"
                       -DCTDB_VARDIR=\"%s\"
                       -DCTDB_RUNDIR=\"%s\"''' % (
                    conf.env.CTDB_HELPER_BINDIR,
                    conf.env.CTDB_LOGDIR,
                    conf.env.CTDB_ETCDIR,
                    conf.env.CTDB_VARDIR,
                    conf.env.CTDB_RUNDIR))

    conf.env.CTDB_TEST_DATADIR = os.path.join(conf.env.EXEC_PREFIX,
                                              'share/ctdb/tests')
    conf.env.CTDB_TEST_LIBEXECDIR = os.path.join(conf.env.LIBEXECDIR, 'ctdb/tests')

    # Allow unified compilation and separate compilation of utilities
    # to find includes
    if not conf.env.standalone_ctdb:
        conf.ADD_EXTRA_INCLUDES('#include/public #ctdb/include #ctdb')
    else:
        if srcdir == '.':
            # Building from tarball
            conf.ADD_EXTRA_INCLUDES('#include')
        else:
            # Building standalone CTDB from within Samba tree
            conf.ADD_EXTRA_INCLUDES('#ctdb/include')
            conf.ADD_EXTRA_INCLUDES('#ctdb')
        conf.ADD_EXTRA_INCLUDES('#lib #lib/replace')

        conf.DEFINE('HAVE_CONFIG_H', 1, add_to_cflags=True)
        conf.DEFINE('SAMBA_UTIL_CORE_ONLY', 1, add_to_cflags=True)
        conf.SAMBA_CONFIG_H()

    if 'XSLTPROC_MANPAGES' in conf.env and conf.env['XSLTPROC_MANPAGES']:
        conf.env.ctdb_generate_manpages = True
    else:
        conf.env.ctdb_generate_manpages = False

        Logs.info("xsltproc unavailable, checking for pre-built manpages")
        conf.env.ctdb_prebuilt_manpages = []
        manpages = manpages_binary + manpages_misc
        if conf.env.etcd_reclock:
            manpages += manpages_etcd
        if conf.env.HAVE_LIBRADOS:
            manpages += manpages_ceph
        for m in manpages:
            if os.path.exists(os.path.join("doc", m)):
                Logs.info("  %s: yes" % (m))
                conf.env.ctdb_prebuilt_manpages.append(m)
            else:
                Logs.info("  %s: no" % (m))

def gen_ctdb_version(task):
    fp = file(task.outputs[0].bldpath(task.env), 'w')
    fp.write('/* This file is auto-generated from waf */\n')
    fp.write('#include "version.h"\n')
    fp.write('\n')
    fp.write('#define CTDB_VERSION_STRING "%s"\n' % VERSION)
    fp.close()


def build(bld):
    if bld.env.standalone_ctdb:
        # enable building of public headers in the build tree
        bld.env.build_public_headers = 'include/public'

    if bld.env.standalone_ctdb:
        bld.SAMBA_MKVERSION('version.h', '%s/VERSION' % vdir)

    t = bld.SAMBA_GENERATOR('ctdb-version-header',
                            target='include/ctdb_version.h',
                            rule=gen_ctdb_version,
                            dep_vars=['VERSION'])
    t.env.VERSION = VERSION

    bld.env.PKGCONFIGDIR = '${LIBDIR}/pkgconfig'

    bld.RECURSE('lib/replace')
    if bld.CHECK_FOR_THIRD_PARTY():
        bld.RECURSE('third_party/popt')
        if bld.env.standalone_ctdb or bld.CONFIG_GET('SOCKET_WRAPPER'):
            bld.RECURSE('third_party/socket_wrapper')

    bld.RECURSE('lib/tdb_wrap')
    bld.RECURSE('lib/util')
    bld.RECURSE('lib/async_req')

    bld.RECURSE('lib/talloc')
    bld.RECURSE('lib/tevent')
    bld.RECURSE('lib/tdb')

    if bld.env.standalone_ctdb:
        # If a combined build is implemented, CTDB will want to
        # build against samba-util rather than samba-util-core.
        # Similarly, other Samba subsystems expect samba-util.  So,
        # for a standalone build, just define a fake samba-util
        # subsystem that pulls in samba-util-core.
        bld.SAMBA_SUBSYSTEM('samba-util',
                            source='',
                            deps='samba-util-core')

    bld.SAMBA_SUBSYSTEM('ctdb-tcp',
                        source=bld.SUBDIR('tcp',
                                          'tcp_connect.c tcp_init.c tcp_io.c'),
                        includes='include',
                        deps='replace tdb talloc tevent')

    ib_deps = ''
    if bld.env.HAVE_INFINIBAND:
        bld.SAMBA_SUBSYSTEM('ctdb-ib',
                            source=bld.SUBDIR('ib',
                                              '''ibwrapper.c ibw_ctdb.c
                                                 ibw_ctdb_init.c'''),
                            includes='include',
                            deps='replace talloc tevent tdb')
        ib_deps = ' ctdb-ib rdmacm ibverbs'

    if sys.platform.startswith('linux'):
        CTDB_SYSTEM_SRC = bld.SUBDIR('common', 'system_linux.c')
    elif sys.platform.startswith('aix'):
        CTDB_SYSTEM_SRC = bld.SUBDIR('common', 'system_aix.c')
    elif sys.platform.startswith('freebsd'):
        CTDB_SYSTEM_SRC = bld.SUBDIR('common', 'system_freebsd.c')
    elif sys.platform.startswith('gnukfreebsd'):
        CTDB_SYSTEM_SRC = bld.SUBDIR('common', 'system_kfreebsd.c')
    elif sys.platform == 'gnu':
        CTDB_SYSTEM_SRC = bld.SUBDIR('common', 'system_gnu.c')
    else:
        Logs.error("Platform %s not supported" % sys.platform)

    bld.SAMBA_SUBSYSTEM('ctdb-system',
                        source=bld.SUBDIR('common',
                                          'system_common.c system_util.c') +
                               CTDB_SYSTEM_SRC,
                        includes='include',
                        deps='replace talloc tevent tdb pcap samba-util')

    bld.SAMBA_SUBSYSTEM('ctdb-common',
                        source=bld.SUBDIR('common',
                                          '''ctdb_io.c ctdb_util.c ctdb_ltdb.c
                                             sock_io.c'''),
                        includes='include',
                        deps='''replace popt talloc tevent tdb popt ctdb-system
                                ctdb-protocol-util''')

    bld.SAMBA_SUBSYSTEM('ctdb-util',
                        source=bld.SUBDIR('common',
                                          '''db_hash.c srvid.c reqid.c
                                             pkt_read.c pkt_write.c comm.c
                                             logging.c rb_tree.c tunable.c
                                             pidfile.c run_proc.c
                                             hash_count.c run_event.c
                                             sock_client.c version.c'''),
                        deps='''samba-util sys_rw tevent-util
                                replace talloc tevent tdb''')

    bld.SAMBA_SUBSYSTEM('ctdb-protocol',
                        source=bld.SUBDIR('protocol',
                                          '''protocol_header.c protocol_packet.c
                                             protocol_basic.c protocol_types.c
                                             protocol_call.c
                                             protocol_message.c
                                             protocol_control.c
                                             protocol_keepalive.c
                                             protocol_tunnel.c
                                             protocol_client.c
                                             protocol_debug.c
                                             protocol_event.c
                                             protocol_sock.c'''),
                        includes='include',
                        deps='replace talloc tdb')

    bld.SAMBA_SUBSYSTEM('ctdb-protocol-util',
                        source='protocol/protocol_util.c',
                        deps='replace talloc tdb')

    bld.SAMBA_SUBSYSTEM('ctdb-client',
                        source=bld.SUBDIR('client', 'ctdb_client.c'),
                        includes='include',
                        deps='''replace popt talloc tevent tdb
                                samba-util tdb-wrap ctdb-util''')

    bld.SAMBA_SUBSYSTEM('ctdb-client2',
                        source=bld.SUBDIR('client',
                                          '''client_connect.c client_call.c
                                             client_message.c client_control.c
                                             client_message_sync.c
                                             client_control_sync.c
                                             client_db.c client_util.c
                                             client_event.c client_tunnel.c
                                          '''),
                        includes='include',
                        deps='replace talloc tevent tdb tdb-wrap')

    bld.SAMBA_SUBSYSTEM('ctdb-server-util',
                        source=bld.SUBDIR('common',
                                          '''sock_daemon.c'''),
                        deps='''samba-util ctdb-util tevent-util
                                LIBASYNC_REQ replace talloc tevent''')

    bld.SAMBA_SUBSYSTEM('ctdb-ipalloc',
                        source=bld.SUBDIR('server',
                                          '''ipalloc_deterministic.c
                                             ipalloc_nondeterministic.c
                                             ipalloc_lcp2.c
                                             ipalloc_common.c
                                             ipalloc.c
                                          '''),
                        includes='include',
                        deps='ctdb-protocol-util replace talloc tevent')

    bld.SAMBA_BINARY('ctdbd',
                     source='server/ctdbd.c ' +
                               bld.SUBDIR('server',
                                          '''ctdb_daemon.c ctdb_recoverd.c
                                             ctdb_recover.c ctdb_freeze.c
                                             ctdb_tunables.c ctdb_monitor.c
                                             ctdb_server.c ctdb_control.c
                                             ctdb_call.c ctdb_ltdb_server.c
                                             ctdb_traverse.c eventscript.c
                                             ctdb_takeover.c
                                             ctdb_persistent.c ctdb_keepalive.c
                                             ctdb_cluster_mutex.c
                                             ctdb_logging.c
                                             ctdb_uptime.c
                                             ctdb_vacuum.c ctdb_banning.c
                                             ctdb_statistics.c
                                             ctdb_update_record.c
                                             ctdb_lock.c ctdb_fork.c
                                             ctdb_tunnel.c'''),
                     includes='include',
                     deps='''ctdb-client ctdb-common ctdb-system ctdb-protocol
                             ctdb-tcp ctdb-util replace sys_rw popt
                             talloc tevent tdb talloc_report''' +
                          ib_deps,
                     install_path='${SBINDIR}',
                     manpages='ctdbd.1')

    bld.SAMBA_BINARY('ctdb',
                     source='tools/ctdb.c',
                     deps='''ctdb-client2 ctdb-protocol ctdb-protocol-util
                             ctdb-util ctdb-system samba-util sys_rw popt''',
                     install_path='${BINDIR}',
                     manpages='ctdb.1')

    bld.SAMBA_BINARY('ctdb_killtcp',
                     source='tools/ctdb_killtcp.c',
                     deps='''ctdb-protocol-util ctdb-util ctdb-system
                             samba-util replace''',
                     install_path='${CTDB_HELPER_BINDIR}')

    bld.SAMBA_BINARY('ctdb_event',
                     source='tools/ctdb_event.c',
                     deps='''ctdb-client2 ctdb-protocol ctdb-protocol-util
                             ctdb-util ctdb-system samba-util replace''',
                     install_path='${CTDB_HELPER_BINDIR}')

    bld.SAMBA_BINARY('ltdbtool',
                     source='tools/ltdbtool.c',
                     includes='include',
                     deps='tdb',
                     install_path='${BINDIR}',
                     manpages='ltdbtool.1')

    bld.SAMBA_BINARY('ctdb_eventd',
                     source='server/ctdb_eventd.c',
                     deps='''ctdb-server-util ctdb-protocol ctdb-protocol-util
                             ctdb-util samba-util replace popt''',
                     install_path='${CTDB_HELPER_BINDIR}')

    bld.SAMBA_BINARY('ctdb_lock_helper',
                     source='server/ctdb_lock_helper.c',
                     deps='''samba-util sys_rw ctdb-system tevent-util
                             talloc tevent tdb''',
                     includes='include',
                     install_path='${CTDB_HELPER_BINDIR}')

    bld.SAMBA_BINARY('ctdb_recovery_helper',
                     source='server/ctdb_recovery_helper.c',
                     deps='''ctdb-client2 ctdb-protocol ctdb-util
                             samba-util sys_rw replace tdb''',
                     install_path='${CTDB_HELPER_BINDIR}')

    bld.SAMBA_BINARY('ctdb_takeover_helper',
                     source='server/ctdb_takeover_helper.c',
                     deps='''ctdb-client2 ctdb-protocol ctdb-util
                             samba-util sys_rw replace ctdb-ipalloc popt''',
                     install_path='${CTDB_HELPER_BINDIR}')

    bld.SAMBA_BINARY('ctdb_mutex_fcntl_helper',
                     source='server/ctdb_mutex_fcntl_helper.c',
                     deps='sys_rw ctdb-system',
                     includes='include',
                     install_path='${CTDB_HELPER_BINDIR}')

    bld.SAMBA_GENERATOR('ctdb-smnotify-h',
                        source='utils/smnotify/smnotify.x',
                        target='utils/smnotify/smnotify.h',
                        rule='rpcgen -h ${SRC} > ${TGT}')

    xdr_buf_hack = 'sed -e "s@^\([ \t]*register int32_t \*buf\);@\\1 = buf;@"'

    bld.SAMBA_GENERATOR('ctdb-smnotify-x',
                        source='utils/smnotify/smnotify.x',
                        target='utils/smnotify/gen_xdr.c',
                        rule='rpcgen -c ${SRC} | ' + xdr_buf_hack + ' > ${TGT}')

    bld.SAMBA_GENERATOR('ctdb-smnotify-c',
                        source='utils/smnotify/smnotify.x',
                        target='utils/smnotify/gen_smnotify.c',
                        rule='rpcgen -l ${SRC} > ${TGT}')

    bld.SAMBA_BINARY('smnotify',
                     source=bld.SUBDIR('utils/smnotify',
                                       'smnotify.c gen_smnotify.c gen_xdr.c'),
                     deps='ctdb-smnotify-h ctdb-smnotify-c ctdb-smnotify-x popt tirpc',
                     includes='utils utils/smnotify',
                     install_path='${CTDB_HELPER_BINDIR}')

    bld.SAMBA_BINARY('ping_pong',
                     source='utils/ping_pong/ping_pong.c',
                     deps='',
                     install_path='${BINDIR}',
                     manpages='ping_pong.1')

    if bld.env.HAVE_PMDA:
        bld.SAMBA_BINARY('pmdactdb',
                         source='utils/pmda/pmda_ctdb.c',
                         includes='include',
                         deps='''ctdb-client2 ctdb-protocol ctdb-util
                                 samba-util pcp_pmda pcp''',
                         install_path='${CTDB_PMDADIR}')
        bld.INSTALL_FILES('${CTDB_PMDADIR}', 'utils/pmda/Install',
                          destname='Install')
        bld.INSTALL_FILES('${CTDB_PMDADIR}', 'utils/pmda/Remove',
                          destname='Remove')
        bld.INSTALL_FILES('${CTDB_PMDADIR}', 'utils/pmda/pmns',
                          destname='pmns')
        bld.INSTALL_FILES('${CTDB_PMDADIR}', 'utils/pmda/domain.h',
                          destname='domain.h')
        bld.INSTALL_FILES('${CTDB_PMDADIR}', 'utils/pmda/help',
                          destname='help')
        bld.INSTALL_FILES('${CTDB_PMDADIR}', 'utils/pmda/README',
                          destname='README')

    if bld.env.HAVE_LIBRADOS:
        bld.SAMBA_BINARY('ctdb_mutex_ceph_rados_helper',
                         source='utils/ceph/ctdb_mutex_ceph_rados_helper.c',
			 deps='talloc tevent rados ceph-common',
			 includes='include',
			 install_path='${CTDB_HELPER_BINDIR}')

    sed_expr1 = 's|/usr/local/var/lib/ctdb|%s|g'  % (bld.env.CTDB_VARDIR)
    sed_expr2 = 's|/usr/local/etc/ctdb|%s|g'      % (bld.env.CTDB_ETCDIR)
    sed_expr3 = 's|/usr/local/var/log|%s|g'       % (bld.env.CTDB_LOGDIR)
    sed_expr4 = 's|/usr/local/var/run/ctdb|%s|g'  % (bld.env.CTDB_RUNDIR)
    sed_expr5 = 's|/usr/local/sbin|%s|g'          % (bld.env.SBINDIR)
    sed_expr6 = 's|/usr/local/libexec/ctdb|%s|g'  % (bld.env.CTDB_HELPER_BINDIR)
    sed_expr7 = 's|/usr/local/bin|%s|g'           % (bld.env.BINDIR)
    sed_cmdline = '-e "%s" -e "%s" -e "%s" -e "%s" -e "%s" -e "%s" -e "%s"' % \
                       (sed_expr1, sed_expr2, sed_expr3, sed_expr4, sed_expr5,
                        sed_expr6, sed_expr7)

    manpages_extra = manpages_misc
    if bld.env.etcd_reclock:
        manpages_extra += manpages_etcd
    if bld.env.HAVE_LIBRADOS:
        manpages_extra += manpages_ceph
    for f in manpages_binary + manpages_extra:
        x = '%s.xml' % (f)
        bld.SAMBA_GENERATOR(x,
                            source=os.path.join('doc', x),
                            target=x,
                            rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))

    if bld.env.ctdb_generate_manpages:
        bld.MANPAGES(' '.join(manpages_extra), True)
    else:
        for m in bld.env.ctdb_prebuilt_manpages:
            bld.SAMBA_GENERATOR(m,
                                source=os.path.join("doc", m),
                                target=m,
                                rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
            bld.INSTALL_FILES('${MANDIR}/man%s' % m[-1], m)

    bld.SAMBA_GENERATOR('ctdb-onnode',
                        source='tools/onnode',
                        target='onnode',
                        rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
    bld.INSTALL_FILES('${BINDIR}', 'onnode',
                      destname='onnode', chmod=0755)

    bld.SAMBA_GENERATOR('ctdb-diagnostics',
                        source='tools/ctdb_diagnostics',
                        target='ctdb_diagnostics',
                        rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
    bld.INSTALL_FILES('${BINDIR}', 'ctdb_diagnostics',
                      destname='ctdb_diagnostics', chmod=0755)

    if bld.env.etcd_reclock:
        bld.SAMBA_GENERATOR('ctdb-etcd-lock',
                            source='utils/etcd/ctdb_etcd_lock',
                            target='ctdb_etcd_lock',
                            rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
        bld.INSTALL_FILES('${CTDB_HELPER_BINDIR}', 'ctdb_etcd_lock',
                          destname='ctdb_etcd_lock', chmod=0744)

    bld.SAMBA_GENERATOR('ctdb-natgw',
                        source='tools/ctdb_natgw',
                        target='ctdb_natgw',
                        rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
    bld.INSTALL_FILES('${CTDB_HELPER_BINDIR}', 'ctdb_natgw',
                      destname='ctdb_natgw', chmod=0755)

    bld.SAMBA_GENERATOR('ctdb-lvs',
                        source='tools/ctdb_lvs',
                        target='ctdb_lvs',
                        rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
    bld.INSTALL_FILES('${CTDB_HELPER_BINDIR}', 'ctdb_lvs',
                      destname='ctdb_lvs', chmod=0755)

    bld.SAMBA_GENERATOR('ctdbd-wrapper',
                        source='config/ctdbd_wrapper',
                        target='ctdbd_wrapper',
                        rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
    bld.INSTALL_FILES('${SBINDIR}', 'ctdbd_wrapper',
                      destname='ctdbd_wrapper', chmod=0755)

    def SUBDIR_MODE_callback(arg, dirname, fnames):
        for f in fnames:
            fl = os.path.join(dirname, f)
            if os.path.isdir(fl) or os.path.islink(fl):
                continue
            mode = os.lstat(fl).st_mode & 0777
            if arg['trim_path']:
                fl = samba_utils.os_path_relpath(fl, arg['trim_path'])
            arg['file_list'].append([fl, mode])

    def SUBDIR_MODE(path, trim_path=None):
        pd = {'trim_path': trim_path, 'file_list': []}
        os.path.walk(path, SUBDIR_MODE_callback, pd)
        return pd['file_list']

    etc_subdirs = [
        'events.d',
        'nfs-checks.d'
    ]

    if bld.env.standalone_ctdb:
        configdir = 'config'
    else:
        configdir = 'ctdb/config'

    for t in etc_subdirs:
        files = SUBDIR_MODE('%s/%s' % (configdir, t), trim_path=configdir)
        for fmode in files:
            bld.INSTALL_FILES(bld.env.CTDB_ETCDIR, 'config/%s' % fmode[0],
                              destname=fmode[0], chmod=fmode[1])

    bld.SAMBA_GENERATOR('ctdb-functions',
                        source='config/functions',
                        target='functions',
                        rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
    bld.INSTALL_FILES(bld.env.CTDB_ETCDIR, 'functions', destname='functions')

    etc_scripts = [
        'ctdb-crash-cleanup.sh',
        'debug-hung-script.sh',
        'debug_locks.sh',
        'gcore_trace.sh',
        'nfs-linux-kernel-callout',
        'notify.sh',
        'statd-callout'
    ]

    for t in etc_scripts:
        bld.INSTALL_FILES(bld.env.CTDB_ETCDIR, 'config/%s' % t,
                          destname=t, chmod=0755)

    bld.SAMBA_GENERATOR('ctdb-sudoers',
                        source='config/ctdb.sudoers',
                        target='ctdb.sudoers',
                        rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
    bld.INSTALL_FILES('${SYSCONFDIR}/sudoers.d', 'ctdb.sudoers',
                      destname='ctdb')

    bld.INSTALL_FILES('${CTDB_ETCDIR}/notify.d', 'config/notify.d.README',
                      destname='README')

    bld.install_dir(bld.env.CTDB_LOGDIR)
    bld.install_dir(bld.env.CTDB_RUNDIR)
    bld.install_dir(bld.env.CTDB_VARDIR)

    # Unit tests
    ctdb_unit_tests = [
        'db_hash_test',
        'srvid_test',
        'pkt_read_test',
        'pkt_write_test',
        'comm_test',
        'comm_server_test',
        'comm_client_test',
        'pidfile_test',
        'run_proc_test',
        'sock_daemon_test',
        'sock_io_test',
        'hash_count_test',
        'run_event_test',
    ]

    for target in ctdb_unit_tests:
        src = 'tests/src/' + target + '.c'

        bld.SAMBA_BINARY(target,
                         source=src,
                         deps='''talloc tevent tdb tevent-util
                                 LIBASYNC_REQ samba-util sys_rw''',
                         install_path='${CTDB_TEST_LIBEXECDIR}')

    bld.SAMBA_BINARY('reqid_test',
                     source='tests/src/reqid_test.c',
                     deps='samba-util',
                     install_path='${CTDB_TEST_LIBEXECDIR}')

    bld.SAMBA_BINARY('rb_test',
                     source='tests/src/rb_test.c',
                     deps='samba-util talloc',
                     install_path='${CTDB_TEST_LIBEXECDIR}')

    bld.SAMBA_BINARY('ctdb_packet_parse',
                     source='tests/src/ctdb_packet_parse.c',
                     deps='talloc tevent tdb ctdb-protocol',
                     install_path='${CTDB_TEST_LIBEXECDIR}')

    bld.SAMBA_BINARY('porting_tests',
                     source='tests/src/porting_tests.c',
                     deps='samba-util ctdb-system popt',
                     install_path='${CTDB_TEST_LIBEXECDIR}')

    bld.SAMBA_SUBSYSTEM('protocol-tests-common',
                        source=bld.SUBDIR('tests/src',
                                          '''protocol_common.c
                                             protocol_common_ctdb.c
                                             protocol_common_event.c
                                          '''),
                        includes='include',
                        deps='replace popt talloc tevent tdb')

    ctdb_protocol_tests = [
            'protocol_basic_test',
            'protocol_types_test',
            'protocol_ctdb_test',
            'protocol_event_test',
            'protocol_util_test',
            'protocol_types_compat_test',
            'protocol_ctdb_compat_test',
    ]

    for target in ctdb_protocol_tests:
        src = 'tests/src/' + target + '.c'

        bld.SAMBA_BINARY(target,
                         source=src,
                         deps='''protocol-tests-common
                                 samba-util talloc tdb''',
                         install_path='${CTDB_TEST_LIBEXECDIR}')

    bld.SAMBA_SUBSYSTEM('ctdb-tests-common',
                        source=bld.SUBDIR('tests/src',
                                          'cluster_wait.c test_options.c'),
                        includes='include',
                        deps='samba-util replace popt talloc tevent tdb')

    # Test binaries
    ctdb_tests = [
        'g_lock_loop',
        'message_ring',
        'fetch_ring',
        'fetch_loop',
        'fetch_loop_key',
        'fetch_readonly',
        'fetch_readonly_loop',
        'transaction_loop',
        'update_record',
        'update_record_persistent',
        'lock_tdb',
        'dummy_client',
        'tunnel_test',
        'tunnel_cmd',
    ]

    for target in ctdb_tests:
        src = 'tests/src/' + target + '.c'

        bld.SAMBA_BINARY(target,
                         source=src,
                         includes='include',
                         deps='''ctdb-client2 ctdb-protocol ctdb-util
                                 samba-util ctdb-tests-common''',
                         install_path='${CTDB_TEST_LIBEXECDIR}')

    bld.SAMBA_BINARY('ctdb_takeover_tests',
                     source='''tests/src/ctdb_takeover_tests.c
                               tests/src/ipalloc_read_known_ips.c''',
                     deps='''replace popt tdb tevent talloc ctdb-system
                             samba-util tdb-wrap talloc_report
                             ctdb-ipalloc ctdb-protocol ctdb-util''',
                     includes='include',
                     install_path='${CTDB_TEST_LIBEXECDIR}')

    bld.SAMBA_BINARY('fake_ctdbd',
                     source='''tests/src/fake_ctdbd.c
                               tests/src/ipalloc_read_known_ips.c''',
                     deps='''ctdb-util ctdb-protocol ctdb-protocol-util
                             ctdb-system samba-util tevent-util
                             LIBASYNC_REQ popt''',
                     install_path='${CTDB_TEST_LIBEXECDIR}')

    if bld.env.HAVE_INFINIBAND:
        bld.SAMBA_BINARY('ibwrapper_test',
                         source='ib/ibwrapper_test.c',
                         includes='include',
                         deps='replace talloc ctdb-client ctdb-common sys_rw' +
                              ib_deps,
                         install_path='${CTDB_TEST_LIBEXECDIR}')

    if bld.env.HAVE_ROBUST_MUTEXES and sys.platform.startswith('linux'):
        bld.SAMBA_BINARY('test_mutex_raw',
                         source='tests/src/test_mutex_raw.c',
                         deps='pthread',
                         install_path='${CTDB_TEST_LIBEXECDIR}')

    test_subdirs = [
        'complex',
        'cunit',
        'eventd',
        'events.d',
        'eventscripts',
        'onnode',
        'shellcheck',
        'simple',
        'takeover',
        'takeover_helper',
        'tool'
    ]

    if bld.env.standalone_ctdb:
        testdir = 'tests'
    else:
        testdir = 'ctdb/tests'

    for t in test_subdirs:
        files = SUBDIR_MODE('%s/%s' % (testdir, t), trim_path=testdir)
        for fmode in files:
            bld.INSTALL_FILES(bld.env.CTDB_TEST_DATADIR, 'tests/%s' % fmode[0],
                              destname=fmode[0], chmod=fmode[1])

    # Install tests/scripts directory without test_wrap
    test_scripts = [
        'common.sh',
        'integration.bash',
        'unit.sh'
    ]

    for t in test_scripts:
        bld.INSTALL_FILES(bld.env.CTDB_TEST_DATADIR,
                          os.path.join('tests/scripts', t),
                          destname=os.path.join('scripts', t))

    sed_expr = 's@^TEST_SCRIPTS_DIR=.*@&\\nexport TEST_BIN_DIR=\"%s\"@' % (
               bld.env.CTDB_TEST_LIBEXECDIR)
    bld.SAMBA_GENERATOR('ctdb-test-wrap',
                        source='tests/scripts/test_wrap',
                        target='test_wrap',
                        rule='sed -e "%s" ${SRC} > ${TGT}' % sed_expr)
    bld.INSTALL_FILES(bld.env.CTDB_TEST_DATADIR+"/scripts", 'test_wrap',
                      destname='test_wrap', chmod=0755)

    bld.SAMBA_GENERATOR('ctdb-test-script-install-paths',
                        source='tests/scripts/script_install_paths.sh',
                        target='script_install_paths.sh',
                        rule='sed %s ${SRC} > ${TGT}' % (sed_cmdline))
    bld.INSTALL_FILES(bld.env.CTDB_TEST_DATADIR+"/scripts",
                      'script_install_paths.sh',
                      destname='script_install_paths.sh', chmod=0644)

    sed_expr1 = 's@^\(export %s\)=.*@\\1=%s\\nexport %s=\"%s\"@''' % (
                    'CTDB_TEST_DIR', bld.env.CTDB_TEST_DATADIR,
                    'TEST_BIN_DIR', bld.env.CTDB_TEST_LIBEXECDIR)
    sed_expr2 = 's@^\(export CTDB_TESTS_ARE_INSTALLED\)=false@\\1=true@'
    bld.SAMBA_GENERATOR('ctdb-test-runner',
                        source='tests/run_tests.sh',
                        target='ctdb_run_tests.sh',
                        rule='sed -e "%s" -e "%s" ${SRC} > ${TGT}' % (
                             sed_expr1, sed_expr2))
    bld.INSTALL_FILES('${BINDIR}', 'ctdb_run_tests.sh',
                      destname='ctdb_run_tests', chmod=0755)
    bld.symlink_as(os.path.join(bld.env.BINDIR, 'ctdb_run_cluster_tests'),
                   'ctdb_run_tests')

    test_eventscript_links = [
        'events.d',
        'functions',
        'nfs-checks.d',
        'nfs-linux-kernel-callout',
        'statd-callout'
    ]

    test_link_dir = os.path.join(bld.env.CTDB_TEST_DATADIR,
                                 'eventscripts/etc-ctdb')
    for t in test_eventscript_links:
        bld.symlink_as(os.path.join(test_link_dir, t),
                       os.path.join(bld.env.CTDB_ETCDIR, t))

    # Tests that use onnode need to overwrite link to in-tree
    # functions file when installed
    bld.symlink_as(os.path.join(bld.env.CTDB_TEST_DATADIR, 'onnode/functions'),
                   os.path.join(bld.env.CTDB_ETCDIR, 'functions'))
    bld.symlink_as(os.path.join(bld.env.CTDB_TEST_DATADIR, 'simple/functions'),
                   os.path.join(bld.env.CTDB_ETCDIR, 'functions'))

    # Need a link to nodes file because $CTDB_BASE is overridden
    bld.symlink_as(os.path.join(bld.env.CTDB_TEST_DATADIR, 'simple/nodes'),
                   os.path.join(bld.env.CTDB_ETCDIR, 'nodes'))


def testonly(ctx):
    cmd = 'tests/run_tests.sh -V tests/var'
    ret = samba_utils.RUN_COMMAND(cmd)
    if ret != 0:
        print('tests exited with exit status %d' % ret)
        sys.exit(ret)


def test(ctx):
    import Scripting
    Scripting.commands.append('build')
    Scripting.commands.append('testonly')


def autotest(ctx):
    env = samba_utils.LOAD_ENVIRONMENT()
    cmd = 'tests/run_tests.sh -e -S %s -C' % env.SOCKET_WRAPPER_SO_PATH
    ret = samba_utils.RUN_COMMAND(cmd)
    if ret != 0:
        print('autotest exited with exit status %d' % ret)
        sys.exit(ret)


def show_version(ctx):
    print VERSION


def manpages(ctx):
    BASE_URL = 'http://docbook.sourceforge.net/release/xsl/current'
    MAN_XSL = '%s/manpages/docbook.xsl' % BASE_URL
    HTML_XSL = '%s/html/docbook.xsl' % BASE_URL
    CMD_TEMPLATE = 'xsltproc --xinclude -o %s --nonet %s %s'
    manpages = manpages_binary + manpages_misc + manpages_etcd + manpages_ceph
    for t in manpages:
        cmd = CMD_TEMPLATE % ('doc/%s' % t, MAN_XSL, 'doc/%s.xml' % t)
        ret = samba_utils.RUN_COMMAND(cmd)
        if ret != 0:
            print('Command %s failed with exit status %d' % (cmd, ret))
            sys.exit(ret)

        cmd = CMD_TEMPLATE % ('doc/%s.html' % t, HTML_XSL, 'doc/%s.xml' % t)
        ret = samba_utils.RUN_COMMAND(cmd)
        if ret != 0:
            print('Command %s failed with exit status %d' % (cmd, ret))
            sys.exit(ret)


def distonly(ctx):
    samba_dist.DIST_FILES('VERSION:VERSION', extend=True)

    distfile = file('.distversion', 'w')
    for field in version.vcs_fields:
        distfile.write('%s=%s\n' % (field, str(version.vcs_fields[field])))
    distfile.close()
    samba_dist.DIST_FILES('ctdb/.distversion:.distversion', extend=True)

    t = 'ctdb.spec'
    sed_expr1 = 's/@VERSION@/%s/g' % VERSION
    sed_expr2 = 's/@RELEASE@/%s/g' % '1'
    cmd = 'sed -e "%s" -e "%s" packaging/RPM/ctdb.spec.in > %s' % (
        sed_expr1, sed_expr2, t)
    ret = samba_utils.RUN_COMMAND(cmd)
    if ret != 0:
        print('Command "%s" failed with exit status %d' % (cmd, ret))
        sys.exit(ret)
    samba_dist.DIST_FILES('ctdb/%s:%s' % (t, t), extend=True)

    manpages = manpages_binary + manpages_misc + manpages_etcd + manpages_ceph
    for t in manpages:
        samba_dist.DIST_FILES('ctdb/doc/%s:doc/%s' % (t, t), extend=True)
        samba_dist.DIST_FILES('ctdb/doc/%s.html:doc/%s.html' % (t, t),
                              extend=True)

    samba_dist.dist()


def dist():
    import Scripting
    Scripting.commands.append('manpages')
    Scripting.commands.append('distonly')


def rpmonly(ctx):
    opts = os.getenv('RPM_OPTIONS') or ''
    cmd = 'rpmbuild -ta --clean --rmsource %s ctdb-%s.tar.gz' % (opts, VERSION)
    ret = samba_utils.RUN_COMMAND(cmd)
    if ret != 0:
        print('rpmbuild exited with exit status %d' % ret)
        sys.exit(ret)


def rpm(ctx):
    import Scripting
    Scripting.commands.append('manpages')
    Scripting.commands.append('distonly')
    Scripting.commands.append('rpmonly')


def ctags(ctx):
    "build 'tags' file using ctags"
    import Utils
    source_root = os.path.dirname(Utils.g_module.root_path)
    cmd = 'ctags $(find %s -name "*.[ch]")' % source_root
    print("Running: %s" % cmd)
    ret = samba_utils.RUN_COMMAND(cmd)
    if ret != 0:
        print('ctags failed with exit status %d' % ret)
        sys.exit(ret)