a3fcc8c53c93bbe26795303c1ecd323c7fef33e5
[dcpomatic.git] / cscript
1 # -*- mode: python -*-
2 #
3 #    Copyright (C) 2012-2022 Carl Hetherington <cth@carlh.net>
4 #
5 #    This file is part of DCP-o-matic.
6 #
7 #    DCP-o-matic is free software; you can redistribute it and/or modify
8 #    it under the terms of the GNU General Public License as published by
9 #    the Free Software Foundation; either version 2 of the License, or
10 #    (at your option) any later version.
11 #
12 #    DCP-o-matic is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU General Public License for more details.
16 #
17 #    You should have received a copy of the GNU General Public License
18 #    along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 from __future__ import print_function
22 import glob
23 import shutil
24 import os
25 import copy
26 import json
27
28 deb_build_depends = dict()
29
30 deb_build_depends_base = ['debhelper', 'g++', 'pkg-config', 'libsndfile1-dev', 'libgtk2.0-dev', 'libx264-dev']
31
32 for v in ['16.04', '18.04', '20.04', '20.10', '21.04', '21.10']:
33     deb_build_depends[v] = copy.deepcopy(deb_build_depends_base)
34     deb_build_depends[v].extend(['libssh-dev', 'python'])
35 for v in ['22.04', '22.10']:
36     deb_build_depends[v] = copy.deepcopy(deb_build_depends_base)
37     deb_build_depends[v].extend(['libssh-dev', 'python3.10'])
38 for v in ['9', '10']:
39     deb_build_depends[v] = copy.deepcopy(deb_build_depends_base)
40     deb_build_depends[v].extend(['libssh-gcrypt-dev', 'python'])
41 for v in ['11']:
42     deb_build_depends[v] = copy.deepcopy(deb_build_depends_base)
43     deb_build_depends[v].extend(['libssh-gcrypt-dev', 'python3.9'])
44 deb_build_depends['unstable'] = copy.deepcopy(deb_build_depends_base)
45 deb_build_depends['unstable'].extend(['python3'])
46
47 deb_depends = dict()
48 deb_depends_gui = dict()
49
50 deb_depends_base = ['libc6', 'libsndfile1', 'libsamplerate0', 'libxmlsec1', 'libxmlsec1-openssl', 'libgtk2.0-0']
51
52 deb_depends['16.04'] = copy.deepcopy(deb_depends_base)
53 deb_depends['16.04'].extend(['libboost-filesystem1.58.0',
54                              'libboost-thread1.58.0',
55                              'libboost-regex1.58.0',
56                              'libxml++2.6-2v5',
57                              'libboost-date-time1.58.0',
58                              'libzip4',
59                              'libcairomm-1.0-1v5',
60                              'libpangomm-1.4-1v5',
61                              'libicu55',
62                              'libnettle6',
63                              'libssh-4',
64                              'libx264-148',
65                              'libcurl3',
66                              'libxerces-c3.1'])
67
68 deb_depends['18.04'] = copy.deepcopy(deb_depends_base)
69 deb_depends['18.04'].extend(['libboost-filesystem1.65.1',
70                              'libboost-thread1.65.1',
71                              'libboost-regex1.65.1',
72                              'libboost-date-time1.65.1',
73                              'libcairomm-1.0-1v5',
74                              'libpangomm-1.4-1v5',
75                              'libxml++2.6-2v5',
76                              'libzip4',
77                              'libicu60',
78                              'libnettle6',
79                              'libssh-4',
80                              'libx264-152',
81                              'libcurl4',
82                              'libpulse0',
83                              'libxerces-c3.2',
84                              'libnanomsg4'])
85
86 deb_depends['20.04'] = copy.deepcopy(deb_depends_base)
87 deb_depends['20.04'].extend(['libboost-filesystem1.71.0',
88                              'libboost-thread1.71.0',
89                              'libboost-regex1.71.0',
90                              'libboost-date-time1.71.0',
91                              'libcairomm-1.0-1v5',
92                              'libpangomm-1.4-1v5',
93                              'libxml++2.6-2v5',
94                              'libzip5',
95                              'libicu66',
96                              'libnettle7',
97                              'libssh-4',
98                              'libx264-155',
99                              'libcurl4',
100                              'libpulse0',
101                              'libxerces-c3.2',
102                              'libnanomsg5'])
103
104 deb_depends['21.10'] = copy.deepcopy(deb_depends_base)
105 deb_depends['21.10'].extend(['libboost-filesystem1.74.0',
106                              'libboost-thread1.74.0',
107                              'libboost-regex1.74.0',
108                              'libboost-date-time1.74.0',
109                              'libcairomm-1.0-1v5',
110                              'libpangomm-1.4-1v5',
111                              'libxml++2.6-2v5',
112                              'libzip4',
113                              'libicu67',
114                              'libnettle8',
115                              'libssh-4',
116                              'libx264-160',
117                              'libcurl4',
118                              'libpulse0',
119                              'libxerces-c3.2',
120                              'libnanomsg5',
121                              'libdav1d4'])
122
123 deb_depends['22.04'] = copy.deepcopy(deb_depends_base)
124 deb_depends['22.04'].extend(['libboost-filesystem1.74.0',
125                              'libboost-thread1.74.0',
126                              'libboost-regex1.74.0',
127                              'libboost-date-time1.74.0',
128                              'libcairomm-1.0-1v5',
129                              'libpangomm-1.4-1v5',
130                              'libxml++2.6-2v5',
131                              'libzip4',
132                              'libicu70',
133                              'libnettle8',
134                              'libssh-4',
135                              'libx264-163',
136                              'libcurl4',
137                              'libpulse0',
138                              'libxerces-c3.2',
139                              'libnanomsg5',
140                              'libdav1d5'])
141
142 deb_depends['22.10'] = copy.deepcopy(deb_depends_base)
143 deb_depends['22.10'].extend(['libboost-filesystem1.74.0',
144                              'libboost-thread1.74.0',
145                              'libboost-regex1.74.0',
146                              'libboost-date-time1.74.0',
147                              'libcairomm-1.0-1v5',
148                              'libpangomm-1.4-1v5',
149                              'libxml++2.6-2v5',
150                              'libzip4',
151                              'libicu71',
152                              'libnettle8',
153                              'libssh-4',
154                              'libx264-164',
155                              'libcurl4',
156                              'libpulse0',
157                              'libxerces-c3.2',
158                              'libnanomsg5'])
159
160
161 deb_depends['9'] = copy.deepcopy(deb_depends_base)
162 deb_depends['9'].extend(['libboost-filesystem1.62.0',
163                          'libboost-thread1.62.0',
164                          'libboost-regex1.62.0',
165                          'libboost-date-time1.62.0',
166                          'libxml++2.6-2v5',
167                          'libgtk2.0-0',
168                          'libzip4',
169                          'libcairomm-1.0-1v5',
170                          'libpangomm-1.4-1v5',
171                          'libicu57',
172                          'libssh-4',
173                          'libssh-gcrypt-4',
174                          'libnettle6',
175                          'libx264-148',
176                          'libcurl3',
177                          'libxerces-c3.1'])
178
179 deb_depends_gui['9'] = [ 'libxcb-xfixes0',
180                          'libxcb-shape0',
181                          'libasound2',
182                          'libpulse0' ]
183
184 deb_depends['10'] = copy.deepcopy(deb_depends_base)
185 deb_depends['10'].extend(['libboost-filesystem1.67.0',
186                           'libboost-thread1.67.0',
187                           'libboost-regex1.67.0',
188                           'libboost-date-time1.67.0',
189                           'libxml++2.6-2v5',
190                           'libgtk2.0-0',
191                           'libzip4',
192                           'libcairomm-1.0-1v5',
193                           'libpangomm-1.4-1v5',
194                           'libicu63',
195                           'libssh-4',
196                           'libssh-gcrypt-4',
197                           'libnettle6',
198                           'libx264-155',
199                           'libcurl4',
200                           'libxerces-c3.2',
201                           'libnanomsg5'])
202
203 deb_depends_gui['10'] = [ 'libxcb-xfixes0',
204                           'libxcb-shape0',
205                           'libasound2',
206                           'libpulse0' ]
207
208 deb_depends['11'] = copy.deepcopy(deb_depends_base)
209 deb_depends['11'].extend(['libboost-filesystem1.74.0',
210                           'libboost-thread1.74.0',
211                           'libboost-regex1.74.0',
212                           'libboost-date-time1.74.0',
213                           'libxml++2.6-2v5',
214                           'libzip4',
215                           'libcairomm-1.0-1v5',
216                           'libpangomm-1.4-1v5',
217                           'libicu67',
218                           'libssh-4',
219                           'libssh-gcrypt-4',
220                           'libnettle8',
221                           'libx264-160',
222                           'libcurl4',
223                           'libxerces-c3.2',
224                           'libnanomsg5',
225                           'libdav1d4'])
226
227 deb_depends_gui['11'] = [ 'libxcb-xfixes0',
228                           'libxcb-shape0',
229                           'libasound2',
230                           'libpulse0' ]
231
232 deb_depends['unstable'] = copy.deepcopy(deb_depends_base)
233 deb_depends['unstable'].extend(['libboost-filesystem1.67.0',
234                                 'libboost-thread1.67.0',
235                                 'libboost-regex1.67.0',
236                                 'libboost-date-time1.67.0',
237                                 'libxml++2.6-2v5',
238                                 'libgtk2.0-0',
239                                 'libzip4',
240                                 'libicu63',
241                                 'libnettle6',
242                                 'libx264-155',
243                                 'libcurl4',
244                                 'libxerces-c3.2',
245                                 'libdav1d4'])
246
247 def can_build_disk(target):
248     # We can build dcpomatic2_disk on platforms that have Boost process and can build the lwext4
249     # library.  For now, just whitelist good ones here.
250     #
251     # - Lots of Linux distros (including Ubuntu 16.04) don't have a new enough boost (1.64 or above)
252     # - On Centos 6 we can't build lwext4 because it needs a new CMake which Centos 6's g++ is not new enough to build.
253     # - On Centos 7 there is a build error in lwext4 related to __unused
254     if target.platform == 'windows':
255         return True
256     if target.platform == 'osx':
257         return True
258     if target.platform == 'linux':
259         if target.distro == 'ubuntu' and target.version != '16.04':
260             return True
261         if target.distro == 'debian' and target.version != '9':
262             return True
263         if target.detail == 'appimage':
264             return True 
265         if target.distro == 'fedora' and int(target.version) >= 31:
266             return True
267         if target.distro == 'centos' and target.version != '7':
268             return True
269         if target.distro == 'mageia':
270             return True
271     return False
272
273 def packages(name, packages, f):
274     s = '%s: ' % name
275     for p in packages:
276         s += str(p) + ', '
277     print(s[:-2], file=f)
278
279 def make_control(debian_version, bits, filename, debug, gui):
280     f = open(filename, 'w')
281     print('Source: dcpomatic', file=f)
282     print('Section: video', file=f)
283     print('Priority: extra', file=f)
284     print('Maintainer: Carl Hetherington <carl@dcpomatic.com>', file=f)
285     packages('Build-Depends', deb_build_depends[debian_version], f)
286     print('Standards-Version: 3.9.3', file=f)
287     print('Homepage: https://dcpomatic.com/', file=f)
288     print('', file=f)
289     suffix = '' if gui else '-cli'
290     print(f'Package: dcpomatic{suffix}', file=f)
291     if gui:
292         print('Replaces: dcpomatic-cli', file=f)
293     if bits == 32:
294         print('Architecture: i386', file=f)
295     else:
296         print('Architecture: amd64', file=f)
297
298     pkg = deb_depends[debian_version]
299     if gui and debian_version in deb_depends_gui:
300         pkg.extend(deb_depends_gui[debian_version])
301
302     packages('Depends', pkg, f)
303
304     print('Description: Generator of Digital Cinema Packages (DCPs)', file=f)
305     print('  DCP-o-matic generates Digital Cinema Packages (DCPs) from videos, images,', file=f)
306     print('  sound and subtitle files.  You can use it to make content for playback on DCI-compliant', file=f)
307     print('  cinema projectors.', file=f)
308     if not gui:
309         print('  This package contains the command-line tools only.', file=f)
310
311     if debug:
312         print('', file=f)
313         print(f'Package: dcpomatic{suffix}-dbg', file=f)
314         if bits == 32:
315             print('Architecture: i386', file=f)
316         else:
317             print('Architecture: amd64', file=f)
318         print('Section: debug', file=f)
319         print('Priority: extra', file=f)
320         packages('Depends', pkg, f)
321         print('Description: debugging symbols for dcpomatic', file=f)
322         print('  This package contains the debugging symbols for dcpomatic.', file=f)
323         print('', file=f)
324
325 def make_spec(filename, version, target, options, requires=None):
326     """Make a .spec file for a RPM build"""
327     f = open(filename, 'w')
328     print('Summary:A program that generates Digital Cinema Packages (DCPs) from video and audio files', file=f)
329     print('Name:dcpomatic2', file=f)
330     print('Version:%s' % version, file=f)
331     print('Release:1%{?dist}', file=f)
332     print('License:GPL', file=f)
333     print('Group:Applications/Multimedia', file=f)
334     print('URL:https://dcpomatic.com/', file=f)
335     if requires is not None:
336         print('Requires:%s' % requires, file=f)
337     print('', file=f)
338     print('%description', file=f)
339     print('DCP-o-matic generates Digital Cinema Packages (DCPs) from video and audio ', file=f)
340     print('files for presentation on DCI-compliant digital projectors.', file=f)
341     print('', file=f)
342     print('%files', file=f)
343     print('%{_bindir}/dcpomatic2', file=f)
344     print('%{_bindir}/dcpomatic2_batch', file=f)
345     print('%{_bindir}/dcpomatic2_cli', file=f)
346     print('%{_bindir}/dcpomatic2_create', file=f)
347     print('%{_bindir}/dcpomatic2_editor', file=f)
348     print('%{_bindir}/dcpomatic2_kdm', file=f)
349     print('%{_bindir}/dcpomatic2_server', file=f)
350     print('%{_bindir}/dcpomatic2_server_cli', file=f)
351     print('%{_bindir}/dcpomatic2_kdm_cli', file=f)
352     print('%{_bindir}/dcpomatic2_player', file=f)
353     print('%{_bindir}/dcpomatic2_playlist', file=f)
354     print('%{_bindir}/dcpomatic2_openssl', file=f)
355     print('%{_bindir}/dcpomatic2_combiner', file=f)
356     print('%{_bindir}/dcpomatic2_verify', file=f)
357     if can_build_disk(target):
358         print('%{_bindir}/dcpomatic2_disk', file=f)
359         print('%caps(cap_dac_override=ep) %{_bindir}/dcpomatic2_disk_writer', file=f)
360     print('%{_datadir}/applications/dcpomatic2.desktop', file=f)
361     print('%{_datadir}/applications/dcpomatic2_batch.desktop', file=f)
362     print('%{_datadir}/applications/dcpomatic2_editor.desktop', file=f)
363     print('%{_datadir}/applications/dcpomatic2_server.desktop', file=f)
364     print('%{_datadir}/applications/dcpomatic2_kdm.desktop', file=f)
365     print('%{_datadir}/applications/dcpomatic2_player.desktop', file=f)
366     print('%{_datadir}/applications/dcpomatic2_playlist.desktop', file=f)
367     print('%{_datadir}/applications/dcpomatic2_combiner.desktop', file=f)
368     if can_build_disk(target):
369         print('%{_datadir}/applications/dcpomatic2_disk.desktop', file=f)
370     print('%{_datadir}/dcpomatic2/dcpomatic2_server_small.png', file=f)
371     print('%{_datadir}/dcpomatic2/select_white.png', file=f)
372     print('%{_datadir}/dcpomatic2/select_black.png', file=f)
373     print('%{_datadir}/dcpomatic2/sequence_white.png', file=f)
374     print('%{_datadir}/dcpomatic2/sequence_black.png', file=f)
375     print('%{_datadir}/dcpomatic2/snap_white.png', file=f)
376     print('%{_datadir}/dcpomatic2/snap_black.png', file=f)
377     print('%{_datadir}/dcpomatic2/zoom_white.png', file=f)
378     print('%{_datadir}/dcpomatic2/zoom_black.png', file=f)
379     print('%{_datadir}/dcpomatic2/zoom_all_white.png', file=f)
380     print('%{_datadir}/dcpomatic2/zoom_all_black.png', file=f)
381     print('%{_datadir}/dcpomatic2/tick.png', file=f)
382     print('%{_datadir}/dcpomatic2/no_tick.png', file=f)
383     print('%{_datadir}/dcpomatic2/link.png', file=f)
384     print('%{_datadir}/dcpomatic2/me.jpg', file=f)
385     print('%{_datadir}/dcpomatic2/LiberationSans-Regular.ttf', file=f)
386     print('%{_datadir}/dcpomatic2/LiberationSans-Italic.ttf', file=f)
387     print('%{_datadir}/dcpomatic2/LiberationSans-Bold.ttf', file=f)
388     print('%{_datadir}/dcpomatic2/splash.png', file=f)
389     for r in ['128x128', '16x16', '22x22', '256x256', '32x32', '48x48', '512x512', '64x64']:
390         print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2.png' % r, file=f)
391         print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_batch.png' % r, file=f)
392         print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_editor.png' % r, file=f)
393         print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_kdm.png' % r, file=f)
394         print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_server.png' % r, file=f)
395         print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_player.png' % r, file=f)
396         print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_playlist.png' % r, file=f)
397         print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_disk.png' % r, file=f)
398         print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_combiner.png' % r, file=f)
399     for l in ['de_DE', 'es_ES', 'fr_FR', 'it_IT', 'sv_SE', 'nl_NL', 'ru_RU', 'pl_PL', 'da_DK',
400               'pt_PT', 'pt_BR', 'sk_SK', 'cs_CZ', 'uk_UA', 'zh_CN', 'tr_TR', 'sl_SI', 'hu_HU']:
401         print('%%{_datadir}/locale/%s/LC_MESSAGES/dcpomatic2.mo' % l, file=f)
402         print('%%{_datadir}/locale/%s/LC_MESSAGES/libdcpomatic2-wx.mo' % l, file=f)
403         print('%%{_datadir}/locale/%s/LC_MESSAGES/libdcpomatic2.mo' % l, file=f)
404     print('%{_datadir}/libdcp/tags/*', file=f)
405     print('%{_datadir}/libdcp/xsd/*', file=f)
406     print('%{_datadir}/libdcp/ratings', file=f)
407     print('%{_datadir}/polkit-1/actions/com.dcpomatic.write-drive.policy', file=f)
408     print('', file=f)
409     print('%prep', file=f)
410     print('rm -rf $RPM_BUILD_DIR/dcpomatic-%s' % version, file=f)
411     print('tar xjf $RPM_SOURCE_DIR/dcpomatic-%s.tar.bz2' % version, file=f)
412     print('%build', file=f)
413     print('cd dcpomatic-%s' % version, file=f)
414     print('export PKG_CONFIG_PATH=%s/lib/pkgconfig:%s/lib64/pkgconfig:/usr/local/lib/pkgconfig:/usr/local/lib64/pkgconfig' % (target.directory, target.directory), file=f)
415     print('CXXFLAGS="-I%s/include" LDFLAGS="-L%s/lib" ./waf configure --prefix=%%{buildroot}/usr --destdir=/usr %s' %
416           (target.directory, target.directory, configure_options(target, options, for_package=True)), file=f)
417     print('./waf', file=f)
418     print('%install', file=f)
419     print('cd dcpomatic-%s' % version, file=f)
420     print('./waf install', file=f)
421     print('/bin/cp %s/src/openssl/apps/openssl %%{buildroot}/usr/bin/dcpomatic2_openssl' % target.directory, file=f)
422     print('/bin/mkdir -p %{buildroot}/usr/share/libdcp', file=f)
423     print('/bin/cp -r %s/src/libdcp/tags %%{buildroot}/usr/share/libdcp' % target.directory, file=f)
424     print('/bin/cp -r %s/src/libdcp/xsd %%{buildroot}/usr/share/libdcp' % target.directory, file=f)
425     print('/bin/cp %s/src/libdcp/ratings %%{buildroot}/usr/share/libdcp' % target.directory, file=f)
426     print('/bin/mv %s/bin/dcpverify %%{buildroot}/usr/bin/dcpomatic2_verify' % target.directory, file=f)
427     print('', file=f)
428     print('%post', file=f)
429     print('/bin/touch --no-create %{_datadir}/icons/hicolor &>/dev/null || :', file=f)
430     print('setcap "cap_dac_override+ep cap_sys_admin+ep" /usr/bin/dcpomatic2_disk_writer', file=f)
431     print('', file=f)
432     print('%postun', file=f)
433     print('if [ $1 -eq 0 ] ; then', file=f)
434     print('    /bin/touch --no-create %{_datadir}/icons/hicolor &>/dev/null', file=f)
435     print('    /usr/bin/gtk-update-icon-cache %{_datadir}/icons/hicolor &>/dev/null || :', file=f)
436     print('fi', file=f)
437     print('', file=f)
438     print('%posttrans', file=f)
439     print('/usr/bin/gtk-update-icon-cache %{_datadir}/icons/hicolor &>/dev/null || :', file=f)
440
441 def dependencies(target, options):
442
443     if target.platform == 'linux':
444         ffmpeg_options = { 'shared': False }
445     else:
446         ffmpeg_options = {}
447
448     if target.platform != 'linux' or target.distro != 'arch':
449         deps = [('ffmpeg-cdist', '4721b55de017702b0d1c8ce1163331378905c637', ffmpeg_options)]
450     else:
451         # Use distro-provided FFmpeg on Arch
452         deps = []
453
454     deps.append(('libdcp', 'v1.8.33'))
455     deps.append(('libsub', 'v1.6.39'))
456     deps.append(('leqm-nrt', '93ae9e6'))
457     deps.append(('rtaudio', 'f619b76'))
458     # We get our OpenSSL libraries from the environment, but we
459     # also need a patched openssl binary to make certificates.
460     # This dependency is to get that binary, which is added into
461     # the appropriate place later
462     deps.append(('openssl', '7f29dd5'))
463     if can_build_disk(target):
464         deps.append(('lwext4', 'ee865fa65f05e348cd4e0bce0552a2725ad5663a'))
465     deps.append(('ffcmp', 'da96af56f3ddf074f2044a0cd6e50c95184fd169'))
466
467     return deps
468
469 option_defaults = { "gui": True, "variant": None }
470
471 def configure_options(target, options, for_package=False):
472     opt = ' --warnings-are-errors'
473
474     if for_package or not (
475             (target.platform == 'linux' and target.distro == 'ubuntu' and target.version in ['18.04', '22.04']) or
476             (target.platform == 'osx') or
477             (target.platform == 'windows')
478         ):
479         # Currently we only build tests on macOS, Windows, and some Ubuntu versions
480         opt += ' --disable-tests'
481
482     if target.debug:
483         opt += ' --enable-debug'
484     if target.platform == 'windows':
485         opt += f' --target-windows-{target.bits}'
486     elif target.platform == 'linux':
487         opt += ' --static-dcpomatic --static-wxwidgets --static-ffmpeg --static-dcp --static-sub --static-cxml'
488         if target.distro == 'centos':
489             if target.version == '6.5':
490                 opt += ' --static-boost --static-xmlpp'
491             elif target.version == '7':
492                 opt += ' --workaround-gssapi'
493
494     if not options['gui']:
495         opt += ' --disable-gui'
496
497     if options['variant'] is not None:
498         opt += ' --variant=%s' % options['variant']
499
500     # Build Windows debug versions with static linking as I think gdb works better then
501     if target.debug and target.platform == 'windows':
502         opt += ' --static-dcpomatic'
503
504     if can_build_disk(target):
505         opt += ' --enable-disk'
506
507     if target.platform == 'osx' and target.arch == 'arm64':
508         opt += ' --target-macos-arm64 --wx-config=%s/wx-config' % target.bin
509
510     return opt
511
512 def build(target, options, for_package):
513     if target.platform == 'flatpak':
514         target.checkout_dependencies()
515         prefix = 'https://dcpomatic.com/deps'
516         modules = []
517         modules.append({'name': 'libzip',
518                         'buildsystem': 'cmake',
519                         'sources': [{'type': 'archive',
520                                      'url': '%s/libzip-1.4.0.tar.xz' % prefix,
521                                      'sha256': 'e508aba025f5f94b267d5120fc33761bcd98440ebe49dbfe2ed3df3afeacc7b1'}]})
522         modules.append({'name': 'libsigc++',
523                         'sources': [{'type': 'archive',
524                                      'url': '%s/libsigc++-2.10.0.tar.xz' % prefix,
525                                      'sha256': 'f843d6346260bfcb4426259e314512b99e296e8ca241d771d21ac64f28298d81'}]})
526         modules.append({'name': 'glibmm',
527                         'sources': [{'type': 'archive',
528                                      'url': '%s/glibmm-2.48.1.tar.xz' % prefix,
529                                      'sha256': 'dc225f7d2f466479766332483ea78f82dc349d59399d30c00de50e5073157cdf'}]})
530         modules.append({'name': 'cairomm',
531                         'sources': [{'type': 'archive',
532                                      'url': '%s/cairomm-1.12.2.tar.gz' % prefix,
533                                      'sha256': '45c47fd4d0aa77464a75cdca011143fea3ef795c4753f6e860057da5fb8bd599'}]})
534         modules.append({'name': 'pangomm',
535                         'sources': [{'type': 'archive',
536                                      'url': '%s/pangomm-2.40.1.tar.xz' % prefix,
537                                      'sha256': '9762ee2a2d5781be6797448d4dd2383ce14907159b30bc12bf6b08e7227be3af'}]})
538         modules.append({'name': 'libxml++',
539                         'sources': [{'type': 'archive',
540                                      'url': '%s/libxml++-2.40.1.tar.xz' % prefix,
541                                      'sha256': '4ad4abdd3258874f61c2e2a41d08e9930677976d303653cd1670d3e9f35463e9'}]})
542         modules.append({'name': 'xmlsec1',
543                         'sources': [{'type': 'archive',
544                                      'url': '%s/xmlsec1-1.2.25.tar.gz' % prefix,
545                                      'sha256': '967ca83edf25ccb5b48a3c4a09ad3405a63365576503bf34290a42de1b92fcd2'}]})
546         modules.append({'name': 'openjpeg2',
547                         'buildsystem': 'cmake',
548                         'sources': [{'type': 'dir', 'path': os.path.abspath('../openjpeg2-cdist')}]})
549         modules.append({'name': 'boost',
550                         'buildsystem': 'simple',
551                         'build-commands': [
552                             './bootstrap.sh --prefix=/app',
553                             './b2 install'
554                         ],
555                         'sources': [{'type': 'archive',
556                                      'url': '%s/boost_1_66_0.tar.bz2' % prefix,
557                                      'sha256': '5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9'}]})
558         modules.append({'name': 'asdcplib',
559                         'buildsystem': 'simple',
560                         'build-commands': [
561                             './waf configure --prefix=/app  --libdir=/app/lib build install'
562                         ],
563                         'sources': [{'type': 'dir', 'path': os.path.abspath('../asdcplib-carl')}]})
564         modules.append({'name': 'locked_sstream',
565                         'buildsystem': 'simple',
566                         'build-commands': [
567                             './waf configure --prefix=/app build install'
568                         ],
569                         'sources': [{'type': 'dir', 'path': os.path.abspath('../locked_sstream')}]})
570         modules.append({'name': 'libcxml',
571                         'buildsystem': 'simple',
572                         'build-commands': [
573                             './waf configure --prefix=/app  --libdir=/app/lib build install'
574                         ],
575                         'sources': [{'type': 'dir', 'path': os.path.abspath('../libcxml')}]})
576         modules.append({'name': 'libdcp',
577                         'buildsystem': 'simple',
578                         'build-commands': [
579                             './waf configure --prefix=/app --libdir=/app/lib build install'
580                         ],
581                         'sources': [{'type': 'dir', 'path': os.path.abspath('../libdcp')}]})
582         modules.append({'name': 'libsub',
583                         'buildsystem': 'simple',
584                         'build-commands': [
585                             './waf configure --prefix=/app --libdir=/app/lib build install'
586                         ],
587                         'sources': [{'type': 'dir', 'path': os.path.abspath('../libsub')}]})
588         modules.append({'name': 'rtaudio',
589                         'build-options': {
590                         'config-opts': [
591                             '--prefix=/app',
592                             '--with-pulse',
593                             '--with-alsa'
594                         ]
595                         },
596                         'sources': [{'type': 'dir', 'path': os.path.abspath('../rtaudio-cdist')}]})
597         modules.append({'name': 'wxwidgets',
598                         'sources': [{'type': 'archive',
599                                      'url': '%s/wxWidgets-3.0.3.tar.bz2' % prefix,
600                                      'sha256': '08c8033f48ec1b23520f036cde37b5ae925a6a65f137ded665633ca159b9307b'}]})
601         modules.append({'name': 'libssh',
602                         'buildsystem': 'cmake',
603                         'builddir': True,
604                         'sources': [{'type': 'archive',
605                                      'url': '%s/libssh-0.7.5.tar.xz' % prefix,
606                                      'sha256': '54e86dd5dc20e5367e58f3caab337ce37675f863f80df85b6b1614966a337095'}]})
607         modules.append({'name': 'dcpomatic',
608                         'buildsystem': 'simple',
609                         'build-commands': [
610                             './waf configure --prefix=/app build install'
611                          ],
612                         'build-options': {
613                            'build-args': ['--share=network']
614                         },
615                         'sources': [{'type': 'dir', 'path': os.path.abspath('.')}]})
616         desc = {'app-id': 'com.dcpomatic.DCP-o-matic',
617                 'runtime': 'org.gnome.Sdk',
618                 'runtime-version': '3.26',
619                 'sdk': 'org.gnome.Sdk',
620                 'command': 'dcpomatic2',
621                 'finish-args': ['--socket=x11', '--share=ipc', '--share=network', '--socket=pulseaudio', '--filesystem=host'],
622                 'modules': modules}
623         os.makedirs('build/platform')
624         with open('build/com.dcpomatic.DCP-o-matic.json', 'w') as outfile:
625             json.dump(desc, outfile)
626         target.command('%s --repo=build/platform/repo build/platform/flatpak build/com.dcpomatic.DCP-o-matic.json' % target.flatpak_builder())
627     elif target.platform != 'linux' or target.detail == 'appimage' or not for_package:
628         target.command('./waf configure --prefix=%s %s' % (target.directory, configure_options(target, options, for_package)))
629         target.command('./waf')
630         target.command('./waf install')
631
632 def package_windows(target):
633     identifier = ''
634     if target.version is not None:
635         identifier = '%s.' % target.version
636     identifier += '%d' % target.bits
637     shutil.copyfile('build/platform/windows/installer.%s.nsi' % identifier, 'build/platform/windows/installer2.%s.nsi' % identifier)
638     target.command('sed -i "s~%%resources%%~%s/platform/windows~g" build/platform/windows/installer2.%s.nsi' % (os.getcwd(), identifier))
639     target.command('sed -i "s~%%graphics%%~%s/graphics~g" build/platform/windows/installer2.%s.nsi' % (os.getcwd(), identifier))
640     target.command('sed -i "s~%%static_deps%%~%s~g" build/platform/windows/installer2.%s.nsi' % (target.windows_prefix, identifier))
641     target.command('sed -i "s~%%cdist_deps%%~%s~g" build/platform/windows/installer2.%s.nsi' % (target.directory, identifier))
642     target.command('sed -i "s~%%mingw%%~%s~g" build/platform/windows/installer2.%s.nsi' % (target.environment_prefix, identifier))
643     target.command('sed -i "s~%%binaries%%~%s/build~g" build/platform/windows/installer2.%s.nsi' % (os.getcwd(), identifier))
644     target.command('sed -i "s~%%bits%%~32~g" build/platform/windows/installer2.%s.nsi' % identifier)
645     target.command('makensis build/platform/windows/installer2.%s.nsi' % identifier)
646     return os.path.abspath(glob.glob('build/platform/windows/*%s*.exe' % target.bits)[0])
647
648 def package_debian(target, cpu, version, options):
649     make_control(target.version, target.bits, 'debian/control', target.debug, options['gui'])
650     if target.version != '9' and target.version != '16.04' and options['gui']:
651         with open('debian/postinst', 'w') as f:
652             print('#!/bin/sh', file=f)
653             # Get the required capability to write to disks
654             print('setcap "cap_dac_override+ep cap_sys_admin+ep" /usr/bin/dcpomatic2_disk_writer', file=f)
655     target.command('./waf dist')
656     f = open('debian/files', 'w')
657     suffix = '' if options['gui'] else '-cli'
658     print(f'dcpomatic{suffix}_{version}-1_{cpu}.deb video extra', file=f)
659     shutil.rmtree('build/deb', ignore_errors=True)
660
661     os.makedirs('build/deb')
662     os.chdir('build/deb')
663     shutil.move('../../dcpomatic-%s.tar.bz2' % version, 'dcpomatic_%s.orig.tar.bz2' % version)
664     target.command('tar xjf dcpomatic_%s.orig.tar.bz2' % version)
665     os.chdir('dcpomatic-%s' % version)
666     target.set('EMAIL', 'carl@dcpomatic.com')
667     target.command('dch -b -v %s-1 "New upstream release."' % version)
668     target.set('CDIST_LINKFLAGS', target.get('LINKFLAGS'))
669     target.set('CDIST_CXXFLAGS', target.get('CXXFLAGS'))
670     target.set('CDIST_PKG_CONFIG_PATH', target.get('PKG_CONFIG_PATH'))
671     target.set('CDIST_DIRECTORY', target.directory)
672
673     target.set('CDIST_CONFIGURE', '"' + configure_options(target, options, for_package=True) + '"')
674     target.set('CDIST_PACKAGE', f'dcpomatic{suffix}')
675     if not target.debug:
676         target.set('CDIST_DEBUG_PACKAGE_FLAG', '--no-ddebs')
677
678     target.command('dpkg-buildpackage -uc -us')
679
680     debs = []
681     for p in glob.glob('../*.deb'):
682         debs.append(os.path.abspath(p))
683
684     return debs
685
686 def package_rpm(target, cpu, version, options):
687     topdir = os.path.realpath('build/rpmbuild')
688     os.makedirs('%s/BUILD' % topdir)
689     os.makedirs('%s/RPMS' % topdir)
690     os.makedirs('%s/SOURCES' % topdir)
691     os.makedirs('%s/SPECS' % topdir)
692     os.makedirs('%s/SRPMS' % topdir)
693
694     target.command('./waf dist')
695     shutil.copyfile(
696         "%s/src/dcpomatic/dcpomatic-%s.tar.bz2" % (target.directory, version),
697         "%s/SOURCES/dcpomatic-%s.tar.bz2" % (topdir, version)
698         )
699
700     requires = None
701     if target.distro == 'mageia':
702         requires = "lib64xmlsec1-devel lib64canberra-gtk0 libcap-utils"
703
704     make_spec('dcpomatic2.spec', version, target, options, requires)
705     cmd = 'rpmbuild --define "_topdir %s" -bb dcpomatic2.spec' % topdir
706     target.command(cmd)
707     rpms = []
708
709     if cpu == "amd64":
710         cpu = "x86_64"
711     else:
712         cpu = "i686"
713
714     for p in glob.glob('%s/RPMS/%s/*.rpm' % (topdir, cpu)):
715         rpms.append(os.path.abspath(p))
716
717     return rpms
718
719 def make_appimage(target, nice_name, internal_name, version):
720     nice_filename = nice_name.replace(' ', '_')
721     appdir = f'build/{nice_filename}.AppDir'
722     os.makedirs(f'{appdir}/usr/bin')
723     target.command(f'cp {target.directory}/bin/{internal_name} {appdir}/usr/bin')
724     target.command(f'cp {target.directory}/src/openssl/apps/openssl {appdir}/usr/bin/dcpomatic2_openssl')
725     target.command(f'cp {target.directory}/bin/dcpverify {appdir}/usr/bin/dcpomatic2_verify')
726     target.command(f'mkdir -p {appdir}/usr/share/libdcp')
727     target.command(f'cp -r {target.directory}/share/dcpomatic2 {appdir}/usr/share/')
728     target.command(f'cp -r {target.directory}/share/libdcp/xsd {appdir}/usr/share/libdcp/')
729     target.command(f'cp -r {target.directory}/share/libdcp/tags {appdir}/usr/share/libdcp/')
730     target.command(f'cp {target.directory}/share/libdcp/ratings {appdir}/usr/share/libdcp/')
731     lib = 'usr/lib/x86_64-linux-gnu'
732     target.command(f'mkdir -p build/{nice_filename}.AppDir/{lib}/gdk-pixbuf-2.0/2.10.0')
733     target.command(f'cp -a /{lib}/gdk-pixbuf-2.0 build/{nice_filename}.AppDir/usr/lib/x86_64-linux-gnu/')
734     target.command('apt update')
735     for package in ['libc6', 'libglib2.0-0', 'gnome-settings-daemon-schemas', 'librsvg2-common', 'libgdk-pixbuf2.0-0', 'libpango-1.0-0', 'libpangoft2-1.0-0', 'libpangocairo-1.0-0']:
736         target.command(f'apt download {package}')
737         target.command(f'dpkg-deb -x {package}*.deb {appdir}')
738     target.command(f'glib-compile-schemas {appdir}/usr/share/glib-2.0/schemas')
739     target.command(f'sed -i -e "s|/usr/lib/x86_64-linux-gnu/gdk-pixbuf-.*/.*/loaders/||g" {appdir}/usr/lib/x86_64-linux-gnu/gdk-pixbuf-*/*/loaders.cache')
740     # Stop anything loading from outside the AppImage
741     target.command(f'sed -i -e "s|/usr|/xxx|g" {appdir}/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2')
742
743     if internal_name == 'dcpomatic2_disk':
744         target.command(f'mkdir -p {appdir}/usr/share/polkit-1/actions')
745         target.command(f'cp {target.directory}/share/polkit-1/actions/com.dcpomatic.write-drive.policy {appdir}/usr/share/polkit-1/actions')
746
747     with open(f'{appdir}/AppRun', 'w') as f:
748         print('#!/bin/bash', file=f)
749         print('export PATH=$APPDIR/usr/bin:$PATH', file=f)
750         print('export XDG_DATA_DIRS="$APPDIR/usr/share/:/usr/share/:$XDG_DATA_DIRS"', file=f)
751         print('export GDK_PIXBUF_MODULEDIR=$(readlink -f "$APPDIR"/usr/lib/x86_64-linux-gnu/gdk-pixbuf-*/*/loaders/ )', file=f)
752         print('export GDK_PIXBUF_MODULE_FILE=$(readlink -f "$APPDIR"/usr/lib/x86_64-linux-gnu/gdk-pixbuf-*/*/loaders.cache )', file=f)
753         print('export LD_LIBRARY_PATH=$GDK_PIXBUF_MODULEDIR:$APPDIR/usr/lib:$APPDIR/usr/lib/x86_64-linux-gnu', file=f)
754         print(f'"$APPDIR"/usr/bin/{internal_name} $@', file=f)
755     target.command(f'chmod a+rx {appdir}/AppRun')
756     with open(f'{appdir}/{internal_name}.desktop', 'w') as f:
757         print('[Desktop Entry]', file=f)
758         print('Type=Application', file=f)
759         print('Categories=AudioVideo;', file=f)
760         print(f'Name={nice_name}', file=f)
761         print(f'Icon={internal_name}', file=f)
762     target.command(f'cp graphics/linux/256/{internal_name}.png {appdir}')
763     target.command(f'linuxdeploy-x86_64.AppImage --appdir {appdir}')
764     target.command(f'appimagetool-x86_64.AppImage {appdir}')
765     target.command(f'mv {nice_filename}-x86_64.AppImage build/{nice_filename}-{version}-x86_64.AppImage')
766     return os.path.abspath(f'build/{nice_filename}-{version}-x86_64.AppImage')
767
768 def package(target, version, options):
769     """version: DCP-o-matic version string"""
770     if target.platform == 'windows':
771         return package_windows(target)
772     elif target.platform == 'linux':
773         if target.detail == 'appimage':
774             out = []
775             out.append(make_appimage(target, 'DCP-o-matic', 'dcpomatic2', version))
776             out.append(make_appimage(target, 'DCP-o-matic Player', 'dcpomatic2_player', version))
777             out.append(make_appimage(target, 'DCP-o-matic Playlist Editor', 'dcpomatic2_playlist', version))
778             out.append(make_appimage(target, 'DCP-o-matic KDM Creator', 'dcpomatic2_kdm', version))
779             out.append(make_appimage(target, 'DCP-o-matic Batch Converter', 'dcpomatic2_batch', version))
780             out.append(make_appimage(target, 'DCP-o-matic Encode Server', 'dcpomatic2_server', version))
781             out.append(make_appimage(target, 'DCP-o-matic Combiner', 'dcpomatic2_combiner', version))
782             out.append(make_appimage(target, 'DCP-o-matic Editor', 'dcpomatic2_editor', version))
783             return out
784         else:
785             if target.bits == 32:
786                 cpu = 'i386'
787             else:
788                 cpu = 'amd64'
789
790             if target.distro == 'debian' or target.distro == 'ubuntu':
791                 return package_debian(target, cpu, version, options)
792             elif target.distro == 'centos' or target.distro == 'fedora' or target.distro == 'mageia':
793                 return package_rpm(target, cpu, version, options)
794     elif target.platform == 'osx':
795         archs = '-a ' + ' -a '.join(f'{t.arch}/{t.deployment}' for t in target.sub_targets)
796         cmd = 'bash platform/osx/make_dmg.sh -e %s -r %s -i %s -p %s %s' % (target.environment_prefix, target.directory, target.apple_id, target.apple_password, archs)
797         if 'part' in options:
798             cmd += ' -b ' + options['part']
799         target.command(cmd)
800         packages = []
801         for x in glob.glob('build/platform/osx/DCP-o-matic*.dmg'):
802             a = os.path.abspath(x)
803             if x.find("Player") != -1:
804                 packages.append((a, "com.dcpomatic.player"))
805             elif x.find("Playlist Editor") != -1:
806                 packages.append((a, "com.dcpomatic.playlist"))
807             elif x.find("KDM Creator") != -1:
808                 packages.append((a, "com.dcpomatic.kdm"))
809             elif x.find("Batch Converter") != -1:
810                 packages.append((a, "com.dcpomatic.batch"))
811             elif x.find("Encode Server") != -1:
812                 packages.append((a, "com.dcpomatic.server"))
813             elif x.find("Disk Writer") != -1:
814                 packages.append((a, "com.dcpomatic.disk"))
815             elif x.find("Combiner") != -1:
816                 packages.append((a, "com.dcpomatic.combiner"))
817             elif x.find("Editor") != -1:
818                 packages.append((a, "com.dcpomatic.editor"))
819             else:
820                 packages.append((a, "com.dcpomatic"))
821         return packages
822     elif target.platform == 'docker':
823         shutil.copyfile(target.deb, 'build/platform/docker')
824         f = open('build/platform/docker/Dockerfile', 'w')
825         print('FROM debian:jessie', file=f)
826         print('MAINTAINER carl@dcpomatic.com', file=f)
827         print('ADD build/platform/docker/dcpomatic_%s-1_amd64.deb /tmp' % (version, version), file=f)
828         print('RUN apt-get -o Acquire:http::Timeout="5" update; exit 0', file=f)
829         print('RUN dpkg -i /tmp/dcpomatic_*.deb; exit 0', file=f)
830         print('RUN apt-get -y -f install', file=f)
831         print('RUN apt-get clean', file=f)
832         print('EXPOSE 6192', file=f)
833         print('CMD ["/usr/bin/dcpomatic2_server_cli", "--verbose"]', file=f)
834         f.close()
835         target.command('docker build build/platform/docker -t dcpomatic-server:%s' % version)
836         target.command('docker save dcpomatic-server:%s -o dcpomatic-server-%s-docker.tar' % (version, version))
837     elif target.platform == 'flatpak':
838         target.command('%s build-bundle build/platform/repo build/dcpomatic_%s.flatpak com.dcpomatic.DCP-o-matic' % (target.flatpak(), version))
839         return os.path.abspath('build/dcpomatic_%s.flatpak' % version)
840
841 def make_pot(target):
842     target.command('./waf pot')
843     return [os.path.abspath('build/src/lib/libdcpomatic.pot'),
844             os.path.abspath('build/src/wx/libdcpomatic-wx.pot'),
845             os.path.abspath('build/src/tools/dcpomatic.pot')]
846
847 def make_manual(target):
848     target.command('make -C doc/manual LIBDCP=../../../libdcp')
849     os.chdir('doc/manual')
850     target.command('pdflatex colour.tex')
851     return [os.path.abspath('pdf'), os.path.abspath('html'), os.path.abspath('colour.pdf')]
852
853 def test(target, options, test):
854     target.set('LC_ALL', 'C')
855     if target.platform == 'windows':
856         cmd = 'run\\tests '
857     else:
858         cmd = 'run/tests --log_level=test_suite '
859     if target.debug:
860         cmd += '--backtrace '
861     if test is not None:
862         cmd += '-t %s' % test
863     target.command(cmd)