xref: /trunk/main/solenv/bin/deliver.pl (revision e28c1c5c7ee9fb9b5b500b5f72d96e08df8962b7)
1:
2eval 'exec perl -wS $0 ${1+"$@"}'
3    if 0;
4#**************************************************************
5#
6#  Licensed to the Apache Software Foundation (ASF) under one
7#  or more contributor license agreements.  See the NOTICE file
8#  distributed with this work for additional information
9#  regarding copyright ownership.  The ASF licenses this file
10#  to you under the Apache License, Version 2.0 (the
11#  "License"); you may not use this file except in compliance
12#  with the License.  You may obtain a copy of the License at
13#
14#    http://www.apache.org/licenses/LICENSE-2.0
15#
16#  Unless required by applicable law or agreed to in writing,
17#  software distributed under the License is distributed on an
18#  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
19#  KIND, either express or implied.  See the License for the
20#  specific language governing permissions and limitations
21#  under the License.
22#
23#**************************************************************
24
25
26
27#
28# deliver.pl - copy from module output tree to solver
29#
30
31use Cwd;
32use File::Basename;
33use File::Copy;
34use File::DosGlob 'glob';
35use File::Path;
36use File::Spec;
37
38#### script id #####
39
40( $script_name = $0 ) =~ s/^.*\b(\w+)\.pl$/$1/;
41
42$id_str = ' $Revision$ ';
43$id_str =~ /Revision:\s+(\S+)\s+\$/
44  ? ($script_rev = $1) : ($script_rev = "-");
45
46
47#### globals ####
48
49### valid actions ###
50# if you add a action 'foo', than add 'foo' to this list and
51# implement 'do_foo()' in the implemented actions area
52@action_list        =   (           # valid actions
53                        'copy',
54                        'dos',
55                        'addincpath',
56                        'linklib',
57                        'mkdir',
58                        'symlink',
59                        'touch'
60                        );
61
62# copy filter: files matching these patterns won't be copied by
63# the copy action
64@copy_filter_patterns = (
65                        );
66
67$strip              = '';
68$is_debug           = 0;
69
70$error              = 0;
71$module             = 0;            # module name
72$repository         = 0;            # parent directory of this module
73$base_dir           = 0;            # path to module base directory
74$dlst_file          = 0;            # path to d.lst
75$ilst_ext           = 'ilst';       # extension of image lists
76$umask              = 22;           # default file/directory creation mask
77$dest               = 0;            # optional destination path
78$common_build       = 0;            # do we have common trees?
79$common_dest        = 0;            # common tree on solver
80
81@action_data        = ();           # LoL with all action data
82@macros             = ();           # d.lst macros
83@addincpath_list    = ();           # files which have to be filtered through addincpath
84@dirlist            = ();           # List of 'mkdir' targets
85@zip_list           = ();           # files which have to be zipped
86@common_zip_list    = ();           # common files which have to be zipped
87@log_list           = ();           # LoL for logging all copy and link actions
88@common_log_list    = ();           # LoL for logging all copy and link actions in common_dest
89$logfiledate        = 0;            # Make log file as old as newest delivered file
90$commonlogfiledate  = 0;            # Make log file as old as newest delivered file
91
92$files_copied       = 0;            # statistics
93$files_unchanged    = 0;            # statistics
94
95$opt_force          = 0;            # option force copy
96$opt_check          = 0;            # do actually execute any action
97$opt_zip            = 0;            # create an additional zip file
98$opt_silent         = 0;            # be silent, only report errors
99$opt_verbose        = 0;            # be verbose (former default behaviour)
100$opt_log            = 1;            # create an additional log file
101$opt_link           = 0;            # hard link files into the solver to save disk space
102$opt_deloutput      = 0;            # delete the output tree for the project once successfully delivered
103$opt_checkdlst      = 0;
104$delete_common      = 1;            # for "-delete": if defined delete files from common tree also
105
106if ($^O ne 'cygwin') {              # iz59477 - cygwin needes a dot "." at the end of filenames to disable
107    $maybedot     = '';             # some .exe transformation magic.
108} else {
109    my $cygvernum = `uname -r`;
110    my @cygvernum = split( /\./, $cygvernum);
111    $cygvernum = shift @cygvernum;
112    $cygvernum .= shift @cygvernum;
113    if ( $cygvernum < 17 ) {
114        $maybedot     = '.';
115    } else {
116        $maybedot     = '';               # no longer works with cygwin 1.7. other magic below.
117    }
118}
119
120($gui       = lc($ENV{GUI}))        || die "Can't determine 'GUI'. Please set environment.\n";
121$tempcounter        = 0;
122
123# zip is default for RE master builds
124$opt_zip = 1 if ( defined($ENV{DELIVER_TO_ZIP}) && uc($ENV{DELIVER_TO_ZIP}) eq 'TRUE' && ! defined($ENV{CWS_WORK_STAMP}));
125
126$has_symlinks       = 0;            # system supports symlinks
127
128for (@action_list) {
129    $action_hash{$_}++;
130}
131
132# trap normal signals (HUP, INT, PIPE, TERM)
133# for clean up on unexpected termination
134use sigtrap 'handler' => \&cleanup_and_die, 'normal-signals';
135
136#### main ####
137
138parse_options();
139init_globals();
140
141print "$script_name -- version: $script_rev\n" if !$opt_silent;
142
143if ( ! $opt_delete ) {
144    if ( $ENV{GUI} eq 'WNT' ) {
145        if ($ENV{COM} eq 'GCC') {
146            initialize_strip() ;
147        };
148    } else {
149        initialize_strip();
150    }
151}
152
153push_default_actions();
154parse_dlst();
155check_dlst() if $opt_checkdlst;
156walk_action_data();
157walk_addincpath_list();
158write_log() if $opt_log;
159zip_files() if $opt_zip;
160cleanup() if $opt_delete;
161delete_output() if $opt_deloutput;
162print_stats();
163
164exit($error);
165
166#### implemented actions #####
167
168sub do_copy
169{
170    # We need to copy two times:
171    # from the platform dependent output tree
172    # and from the common output tree
173    my ($dependent, $common, $from, $to, $file_list);
174    my $line = shift;
175    my $touch = 0;
176
177    $dependent = expand_macros($line);
178    ($from, $to) = split(' ', $dependent);
179    print "copy dependent: from: $from, to: $to\n" if $is_debug;
180    glob_and_copy($from, $to, $touch);
181
182    if ($delete_common && $common_build && ( $line !~ /%COMMON_OUTDIR%/ ) ) {
183        $line =~ s/%__SRC%/%COMMON_OUTDIR%/ig;
184        if ( $line =~ /%COMMON_OUTDIR%/ ) {
185            $line =~ s/%_DEST%/%COMMON_DEST%/ig;
186            $common = expand_macros($line);
187            ($from, $to) = split(' ', $common);
188            print "copy common: from: $from, to: $to\n" if $is_debug;
189            glob_and_copy($from, $to, $touch);
190        }
191    }
192}
193
194sub do_dos
195{
196    my $line = shift;
197
198    my $command = expand_macros($line);
199    if ( $opt_check ) {
200        print "DOS: $command\n";
201    }
202    else {
203        # HACK: remove MACOSX stuff which is wrongly labeled with dos
204        # better: fix broken d.lst
205        return if ( $command =~ /MACOSX/ );
206        $command =~ s#/#\\#g if $^O eq 'MSWin32';
207        system($command);
208    }
209}
210
211sub do_addincpath
212{
213    # just collect all addincpath files, actual filtering is done later
214    my $line = shift;
215    my ($from, $to);
216    my @globbed_files = ();
217
218    $line = expand_macros($line);
219    ($from, $to) = split(' ', $line);
220
221    push( @addincpath_list, @{glob_line($from, $to)});
222}
223
224sub do_linklib
225{
226    my ($lib_base, $lib_major,$from_dir, $to_dir);
227    my $lib = shift;
228    my @globbed_files = ();
229    my %globbed_hash = ();
230
231    print "linklib: $lib\n" if $is_debug;
232    print "has symlinks\n" if ( $has_symlinks && $is_debug );
233
234    return unless $has_symlinks;
235
236    $from_dir = expand_macros('../%__SRC%/lib');
237    $to_dir = expand_macros('%_DEST%/lib%_EXT%');
238
239    @globbed_files = glob("$from_dir/$lib");
240
241    if ( $#globbed_files == -1 ) {
242       return;
243    }
244
245    foreach $lib (@globbed_files) {
246        $lib = basename($lib);
247        if ( $lib =~ /^(lib\S+(\.so|\.dylib))\.(\d+)\.(\d+)(\.(\d+))?$/
248             || $lib =~ /^(lib\S+(\.so|\.dylib))\.(\d+)$/ )
249        {
250           push(@{$globbed_hash{$1}}, $lib);
251        }
252        # libtool's macOS naming puts the version before the extension
253        # (libfoo.4.dylib), unlike ELF's libfoo.so.4 -- same file, opposite order.
254        elsif ( $lib =~ /^(lib\S+)\.(\d+)(\.\d+)?(\.\d+)?(\.dylib)$/ )
255        {
256           push(@{$globbed_hash{"$1$5"}}, $lib);
257        }
258        else {
259            print_warning("invalid library name: $lib");
260        }
261    }
262
263    foreach $lib_base ( sort keys %globbed_hash ) {
264        $lib = get_latest_patchlevel(@{$globbed_hash{$lib_base}});
265
266        if ( $lib =~ /^(lib\S+(\.so|\.dylib))\.(\d+)\.(\d+)(\.(\d+))?$/ )
267        {
268            $lib_major = "$lib_base.$3";
269            $long = 1;
270        }
271        elsif ( $lib =~ /^(lib\S+)\.(\d+)(\.\d+)?(\.\d+)?(\.dylib)$/ )
272        {
273            # macOS dylibs don't carry a separate major-only symlink; the
274            # single unversioned name below is enough.
275            $long = 0;
276        }
277        else
278        {
279            # $lib =~ /^(lib[\w-]+(\.so|\.dylib))\.(\d+)$/;
280            $long = 0;
281        }
282
283        if ( $opt_check ) {
284            if ( $opt_delete ) {
285                print "REMOVE: $to_dir/$lib_major\n" if $long;
286                print "REMOVE: $to_dir/$lib_base\n";
287            }
288            else {
289                print "LINKLIB: $to_dir/$lib -> $to_dir/$lib_major\n" if $long;
290                print "LINKLIB: $to_dir/$lib -> $to_dir/$lib_base\n";
291            }
292        }
293        else {
294            if ( $opt_delete ) {
295                print "REMOVE: $to_dir/$lib_major\n" if ($long && $opt_verbose);
296                print "REMOVE: $to_dir/$lib_base\n" if $opt_verbose;
297                unlink "$to_dir/$lib_major" if $long;
298                unlink "$to_dir/$lib_base";
299                if ( $opt_zip ) {
300                    push_on_ziplist("$to_dir/$lib_major") if $long;
301                    push_on_ziplist("$to_dir/$lib_base");
302                }
303                return;
304            }
305            my $symlib;
306            my @symlibs;
307            if ($long)
308            {
309                @symlibs = ("$to_dir/$lib_major", "$to_dir/$lib_base");
310            }
311            else
312            {
313                @symlibs = ("$to_dir/$lib_base");
314            }
315            # remove old symlinks
316            unlink(@symlibs);
317            foreach $symlib (@symlibs) {
318                print "LINKLIB: $lib -> $symlib\n" if $opt_verbose;
319                if ( !symlink("$lib", "$symlib") ) {
320                    print_error("can't symlink $lib -> $symlib: $!",0);
321                }
322                else {
323                    push_on_ziplist($symlib) if $opt_zip;
324                    push_on_loglist("LINK", "$lib", "$symlib") if $opt_log;
325                }
326            }
327        }
328    }
329}
330
331sub do_mkdir
332{
333    my $path = expand_macros(shift);
334    # strip whitespaces from path name
335    $path =~ s/\s$//;
336    if (( ! $opt_delete ) && ( ! -d $path )) {
337        if ( $opt_check ) {
338            print "MKDIR: $path\n";
339        } else {
340            mkpath($path, 0, 0777-$umask);
341            if ( ! -d $path ) {
342                print_error("mkdir: could not create directory '$path'", 0);
343            }
344        }
345    }
346}
347
348sub do_symlink
349{
350    my $line = shift;
351
352    $line = expand_macros($line);
353    ($from, $to) = split(' ',$line);
354    my $fullfrom = $from;
355    if ( dirname($from) eq dirname($to) ) {
356        $from = basename($from);
357    }
358    elsif ( dirname($from) eq '.' ) {
359        # nothing to do
360    }
361    else {
362        print_error("symlink: link must be in the same directory as file",0);
363        return 0;
364    }
365
366    print "symlink: $from, to: $to\n" if $is_debug;
367
368    return unless $has_symlinks;
369
370    if ( $opt_check ) {
371        if ( $opt_delete ) {
372            print "REMOVE: $to\n";
373        }
374        else {
375            print "SYMLINK $from -> $to\n";
376        }
377    }
378    else {
379        print "REMOVE: $to\n" if $opt_verbose;
380        unlink $to;
381        if ( $opt_delete ) {
382            push_on_ziplist($to) if $opt_zip;
383            return;
384        }
385        return unless -e $fullfrom;
386        print "SYMLIB: $from -> $to\n" if $opt_verbose;
387        if ( !symlink("$from", "$to") ) {
388            print_error("can't symlink $from -> $to: $!",0);
389        }
390        else {
391            push_on_ziplist($to) if $opt_zip;
392            push_on_loglist("LINK", "$from", "$to") if $opt_log;
393        }
394    }
395}
396
397sub do_touch
398{
399    my ($from, $to);
400    my $line = shift;
401    my $touch = 1;
402
403    $line = expand_macros($line);
404    ($from, $to) = split(' ', $line);
405    print "touch: $from, to: $to\n" if $is_debug;
406    glob_and_copy($from, $to, $touch);
407}
408
409#### subroutines #####
410
411sub parse_options
412{
413    my $arg;
414    my $dontdeletecommon = 0;
415    $opt_silent = 1 if ( defined $ENV{VERBOSE} && $ENV{VERBOSE} eq 'FALSE');
416    $opt_verbose = 1 if ( defined $ENV{VERBOSE} && $ENV{VERBOSE} eq 'TRUE');
417    while ( $arg = shift @ARGV ) {
418        $arg =~ /^-force$/      and $opt_force  = 1  and next;
419        $arg =~ /^-check$/      and $opt_check  = 1  and $opt_verbose = 1 and next;
420        $arg =~ /^-quiet$/      and $opt_silent = 1  and next;
421        $arg =~ /^-verbose$/    and $opt_verbose = 1 and next;
422        $arg =~ /^-zip$/        and $opt_zip    = 1  and next;
423        $arg =~ /^-delete$/     and $opt_delete = 1  and next;
424        $arg =~ /^-dontdeletecommon$/ and $dontdeletecommon = 1 and next;
425        $arg =~ /^-help$/       and $opt_help   = 1  and $arg = '';
426        $arg =~ /^-link$/       and $ENV{GUI} ne 'WNT' and $opt_link = 1 and next;
427        $arg =~ /^-deloutput$/  and $opt_deloutput = 1 and next;
428        $arg =~ /^-debug$/      and $is_debug   = 1  and next;
429        $arg =~ /^-checkdlst$/  and $opt_checkdlst = 1 and next;
430        print_error("invalid option $arg") if ( $arg =~ /^-/ );
431        if ( $arg =~ /^-/ || $opt_help || $#ARGV > -1 ) {
432            usage(1);
433        }
434        $dest = $arg;
435    }
436    # $dest and $opt_zip or $opt_delete are mutually exclusive
437    if ( $dest and ($opt_zip || $opt_delete) ) {
438        usage(1);
439    }
440    # $opt_silent and $opt_check or $opt_verbose are mutually exclusive
441    if ( ($opt_check or $opt_verbose) and $opt_silent ) {
442        print STDERR "Error on command line: options '-check' and '-quiet' are mutually exclusive.\n";
443        usage(1);
444    }
445    if ($dontdeletecommon) {
446        if (!$opt_delete) {
447            usage(1);
448        }
449        $delete_common = 0;
450    };
451    # $opt_delete implies $opt_force
452    $opt_force = 1 if $opt_delete;
453}
454
455sub init_globals
456{
457    my $ext;
458    ($module, $repository, $base_dir, $dlst_file) =  get_base();
459
460    # for CWS:
461    $module =~ s/\.lnk$//;
462
463    print "Module=$module, Base_Dir=$base_dir, d.lst=$dlst_file\n" if $is_debug;
464
465    $umask = umask();
466    if ( !defined($umask) ) {
467        $umask = 22;
468    }
469
470    my $build_sosl    = $ENV{'BUILD_SOSL'};
471    my $common_outdir = $ENV{'COMMON_OUTDIR'};
472    my $inpath        = $ENV{'INPATH'};
473    my $solarversion  = $ENV{'SOLARVERSION'};
474    my $updater       = $ENV{'UPDATER'};
475    my $updminor      = $ENV{'UPDMINOR'};
476    my $updminorext   = $ENV{'UPDMINOREXT'};
477    my $work_stamp    = $ENV{'WORK_STAMP'};
478
479    $::CC_PATH=(fileparse( $ENV{"CC"}))[1];
480
481    # special security check for release engineers
482    if ( defined($updater) && !defined($build_sosl) && !$opt_force) {
483        my $path = getcwd();
484        if ( $path !~ /$work_stamp/io ) {
485            print_error("can't deliver from local directory to SOLARVERSION");
486            print STDERR "\nDANGER! Release Engineer:\n";
487            print STDERR "do you really want to deliver from $path to SOLARVERSION?\n";
488            print STDERR "If so, please use the -force switch\n\n";
489            exit(7);
490        }
491    }
492
493    # do we have a valid environment?
494    if ( !defined($inpath) ) {
495            print_error("no environment", 0);
496            exit(3);
497    }
498
499    $ext = "";
500    if ( ($updminor) && !$dest ) {
501        $ext = "$updminorext";
502    }
503
504    # Do we have common trees?
505    if ( defined($ENV{'common_build'}) && $ENV{'common_build'} eq 'TRUE' ) {
506        $common_build = 1;
507        if ((defined $common_outdir) && ($common_outdir ne "")) {
508            $common_outdir = $common_outdir . ".pro" if $inpath =~ /\.pro$/;
509            if ( $dest ) {
510                $common_dest = $dest;
511            } else {
512                $common_dest = "$solarversion/$common_outdir";
513                $dest = "$solarversion/$inpath";
514            }
515        } else {
516            print_error("common_build defined without common_outdir", 0);
517            exit(6);
518        }
519    } else {
520        $common_outdir = $inpath;
521        $dest = "$solarversion/$inpath" if ( !$dest );
522        $common_dest = $dest;
523    }
524    $dest =~ s#\\#/#g;
525    $common_dest =~ s#\\#/#g;
526
527    # the following macros are obsolete, will be flagged as error
528    # %__WORKSTAMP%
529    # %GUIBASE%
530    # %SDK%
531    # %SOLARVER%
532    # %__OFFENV%
533    # %DLLSUFFIX%'
534    # %OUTPATH%
535    # %L10N_FRAMEWORK%
536    # %UPD%
537
538    # valid macros
539    @macros = (
540                [ '%__PRJROOT%',        $base_dir       ],
541                [ '%__SRC%',            $inpath         ],
542                [ '%_DEST%',            $dest           ],
543                [ '%_EXT%',             $ext            ],
544                [ '%COMMON_OUTDIR%',    $common_outdir  ],
545                [ '%COMMON_DEST%',      $common_dest    ],
546                [ '%GUI%',              $gui            ]
547              );
548
549    # find out if the system supports symlinks
550    $has_symlinks = eval { symlink("",""); 1 };
551}
552
553sub get_base
554{
555    # a module base dir contains a subdir 'prj'
556    # which in turn contains a file 'd.lst'
557    my (@field, $repo, $base, $dlst);
558    my $path = getcwd();
559
560    @field = split(/\//, $path);
561
562    while ( $#field != -1 ) {
563        $base = join('/', @field);
564        $dlst = $base . '/prj/d.lst';
565        last if -e $dlst;
566        pop @field;
567    }
568
569    if ( $#field == -1 ) {
570        print_error("can't find d.lst");
571        exit(2);
572    }
573    else {
574        if ( defined $field[-2] ) {
575            $repo = $field[-2];
576        } else {
577            print_error("Internal error: cannot determine module's parent directory");
578        }
579        return ($field[-1], $repo, $base, $dlst);
580    }
581}
582
583sub parse_dlst
584{
585    my $line_cnt = 0;
586    open(DLST, "<$dlst_file") or die "can't open d.lst";
587    while(<DLST>) {
588        $line_cnt++;
589        tr/\r\n//d;
590        next if /^#/;
591        next if /^\s*$/;
592        if (!$delete_common && /%COMMON_DEST%/) {
593            # Just ignore all lines with %COMMON_DEST%
594            next;
595        };
596        if ( /^\s*(\w+?):\s+(.*)$/ ) {
597            if ( !exists $action_hash{$1} ) {
598                print_error("unknown action: \'$1\'", $line_cnt);
599                exit(4);
600            }
601            push(@action_data, [$1, $2]);
602        }
603        else {
604            if ( /^\s*%(COMMON)?_DEST%\\/ ) {
605                # only copy from source dir to solver, not from solver to solver
606                print_warning("illegal copy action, ignored: \'$_\'", $line_cnt);
607                next;
608            }
609            push(@action_data, ['copy', $_]);
610            # for each resource file (.res) copy its image list (.ilst)
611            if ( /\.res\s/ ) {
612                my $imagelist = $_;
613                $imagelist =~ s/\.res/\.$ilst_ext/g;
614                $imagelist =~ s/\\bin%_EXT%\\/\\res%_EXT%\\img\\/;
615                push(@action_data, ['copy', $imagelist]);
616            }
617        }
618        # call expand_macros()just to find any undefined macros early
619        # real expansion is done later
620        expand_macros($_, $line_cnt);
621    }
622    close(DLST);
623}
624
625sub expand_macros
626{
627    # expand all macros and change backslashes to slashes
628    my $line        = shift;
629    my $line_cnt    = shift;
630    my $i;
631
632    for ($i=0; $i<=$#macros; $i++)  {
633        $line =~ s/$macros[$i][0]/$macros[$i][1]/gi
634    }
635    if ( $line =~ /(%\w+%)/ ) {
636        if ( $1 ne '%OS%' ) {   # %OS% looks like a macro but is not ...
637            print_error("unknown/obsolete macro: \'$1\'", $line_cnt);
638        }
639    }
640    $line =~ s#\\#/#g;
641    return $line;
642}
643
644sub walk_action_data
645{
646    # all actions have to be excuted relative to the prj directory
647    chdir("$base_dir/prj");
648    # dispatch depending on action type
649    for (my $i=0; $i <= $#action_data; $i++) {
650            &{"do_".$action_data[$i][0]}($action_data[$i][1]);
651            if ( $action_data[$i][0] eq 'mkdir' ) {
652                # fill array with (possibly) created directories in
653                # revers order for removal in 'cleanup'
654                unshift @dirlist, $action_data[$i][1];
655            }
656    }
657}
658
659sub glob_line
660{
661    my $from = shift;
662    my $to = shift;
663    my $to_dir = shift;
664    my $replace = 0;
665    my @globbed_files = ();
666
667    if ( ! ( $from && $to ) ) {
668        print_warning("Error in d.lst? source: '$from' destination: '$to'");
669        return \@globbed_files;
670    }
671
672    if ( $to =~ /[\*\?\[\]]/ ) {
673        my $to_fname;
674        ($to_fname, $to_dir) = fileparse($to);
675        $replace = 1;
676    }
677
678    if ( $from =~ /[\*\?\[\]]/ ) {
679        # globbing necessary, no renaming possible
680        my $file;
681        my @file_list = glob($from);
682
683        foreach $file ( @file_list ) {
684            next if ( -d $file); # we only copy files, not directories
685            my ($fname, $dir) = fileparse($file);
686            my $copy = ($replace) ? $to_dir . $fname : $to . '/' . $fname;
687            push(@globbed_files, [$file, $copy]);
688        }
689    }
690    else {
691        # no globbing but renaming possible
692        # #i89066#
693        if (-d $to && -f $from) {
694            my $filename = File::Basename::basename($from);
695            $to .= '/' if ($to !~ /[\\|\/]$/);
696            $to .= $filename;
697        };
698        push(@globbed_files, [$from, $to]);
699    }
700    if ( $opt_checkdlst ) {
701        my $outtree = expand_macros("%__SRC%");
702        my $commonouttree = expand_macros("%COMMON_OUTDIR%");
703        if (( $from !~ /\Q$outtree\E/ ) && ( $from !~ /\Q$commonouttree\E/ )) {
704            print_warning("'$from' does not match any file") if ( $#globbed_files == -1 );
705        }
706    }
707    return \@globbed_files;
708}
709
710
711sub glob_and_copy
712{
713    my $from = shift;
714    my $to = shift;
715    my $touch = shift;
716
717    my @copy_files = @{glob_line($from, $to)};
718
719    for (my $i = 0; $i <= $#copy_files; $i++) {
720        next if filter_out($copy_files[$i][0]); # apply copy filter
721        copy_if_newer($copy_files[$i][0], $copy_files[$i][1], $touch)
722                    ? $files_copied++ : $files_unchanged++;
723    }
724}
725
726sub is_unstripped {
727    my $file_name = shift;
728    my $nm_output;
729
730    if (-f $file_name.$maybedot) {
731        my $file_type = `file $file_name`;
732        # OS X file command doesn't know if a file is stripped or not
733        if (($file_type =~ /not stripped/o) || ($file_type =~ /Mach-O/o) ||
734            (($file_type =~ /PE/o) && ($ENV{GUI} eq 'WNT') &&
735             ($nm_output = `nm $file_name 2>&1`) && $nm_output &&
736             !($nm_output =~ /no symbols/i) && !($nm_output =~ /not recognized/i))) {
737            return '1' if ($file_name =~ /\.bin$/o);
738            return '1' if ($file_name =~ /\.so\.*/o);
739            return '1' if ($file_name =~ /\.dylib\.*/o);
740            return '1' if ($file_name =~ /\.com\.*/o);
741            return '1' if ($file_name =~ /\.dll\.*/o);
742            return '1' if ($file_name =~ /\.exe\.*/o);
743            return '1' if (basename($file_name) !~ /\./o);
744        }
745    };
746    return '';
747}
748
749sub initialize_strip {
750    if ((!defined $ENV{DISABLE_STRIP}) || ($ENV{DISABLE_STRIP} eq "")) {
751        $strip .= 'guw ' if ($^O eq 'cygwin');
752        $strip .= $::CC_PATH if (-e $::CC_PATH.'/strip');
753        $strip .= 'strip';
754        $strip .= " -x" if ($ENV{OS} eq 'MACOSX');
755        $strip .= " -R '.comment' -s" if ($ENV{OS} eq 'LINUX');
756    };
757};
758
759sub is_jar {
760    my $file_name = shift;
761
762    if (-f $file_name && (( `file $file_name` ) =~ /Zip archive/o)) {
763        return '1' if ($file_name =~ /\.jar\.*/o);
764    };
765    return '';
766}
767
768sub execute_system {
769    my $command = shift;
770    if (system($command)) {
771        print_error("Failed to execute $command");
772        exit($?);
773    };
774};
775
776sub strip_target {
777    my $file = shift;
778    my $temp_file = shift;
779    $temp_file =~ s/\/{2,}/\//g;
780    my $rc = copy($file, $temp_file);
781    execute_system("$strip $temp_file");
782    return $rc;
783};
784
785sub copy_if_newer
786{
787    # return 0 if file is unchanged ( for whatever reason )
788    # return 1 if file has been copied
789    my $from = shift;
790    my $to = shift;
791    my $touch = shift;
792    my $from_stat_ref;
793    my $rc = 0;
794
795    print "testing $from, $to\n" if $is_debug;
796    push_on_ziplist($to) if $opt_zip;
797    push_on_loglist("COPY", "$from", "$to") if $opt_log;
798    return 0 unless ($from_stat_ref = is_newer($from, $to, $touch));
799
800    if ( $opt_delete ) {
801        print "REMOVE: $to\n" if $opt_verbose;
802        $rc = unlink($to) unless $opt_check;
803        return 1 if $opt_check;
804        return $rc;
805    }
806
807    if( !$opt_check && $opt_link ) {
808        # hard link if possible
809        if( link($from, $to) ){
810            print "LINK: $from -> $to\n" if $opt_verbose;
811            return 1;
812        }
813    }
814
815    if( $touch ) {
816       print "TOUCH: $from -> $to\n" if $opt_verbose;
817    }
818    else {
819       print "COPY: $from -> $to\n" if $opt_verbose;
820    }
821
822    return 1 if( $opt_check );
823
824    #
825    # copy to temporary file first and rename later
826    # to minimize the possibility for race conditions
827    local $temp_file = sprintf('%s.%d-%d', $to, $$, time());
828    $rc = '';
829    if (($strip ne '') && (defined $ENV{PROEXT}) && (is_unstripped($from))) {
830        $rc = strip_target($from, $temp_file);
831    } else {
832        $rc = copy($from, $temp_file);
833    };
834    if ( $rc) {
835        if ( is_newer($temp_file, $from, 0) ) {
836            $rc = utime($$from_stat_ref[9], $$from_stat_ref[9], $temp_file);
837            if ( !$rc ) {
838                print_warning("can't update temporary file modification time '$temp_file': $!\n
839                               Check file permissions of '$from'.",0);
840            }
841        }
842        fix_file_permissions($$from_stat_ref[2], $temp_file);
843        if ( $^O eq 'os2' )
844        {
845            $rc = unlink($to); # YD OS/2 can't rename if $to exists!
846        }
847        # Ugly hack: on windows file locking(?) sometimes prevents renaming.
848        # Until we've found and fixed the real reason try it repeatedly :-(
849        my $try = 0;
850        my $maxtries = 1;
851        $maxtries = 5 if ( $^O eq 'MSWin32' );
852        my $success = 0;
853        while ( $try < $maxtries && ! $success ) {
854            sleep $try;
855            $try ++;
856            $success = rename($temp_file, $to);
857            if ( $^O eq 'cygwin' && $to =~ /\.bin$/) {
858                # hack to survive automatically added .exe for executables renamed to
859                # *.bin - will break if there is intentionally a .bin _and_ .bin.exe file.
860                $success = rename( "$to.exe", $to ) if -f "$to.exe";
861            }
862        }
863        if ( $success ) {
864            # handle special packaging of *.dylib files for Mac OS X
865            if ( $^O eq 'darwin' )
866            {
867                system("macosx-create-bundle", "$to=$from.app") if ( -d "$from.app" );
868                system("ranlib", "$to" ) if ( $to =~ /\.a/ );
869            }
870            if ( $try > 1 ) {
871                print_warning("File '$to' temporarily locked. Dependency bug?");
872            }
873            return 1;
874        }
875        else {
876            print_error("can't rename temporary file to $to: $!",0);
877        }
878    }
879    else {
880        print_error("can't copy $from: $!",0);
881        my $destdir = dirname($to);
882        if ( ! -d $destdir ) {
883            print_error("directory '$destdir' does not exist", 0);
884        }
885    }
886    unlink($temp_file);
887    return 0;
888}
889
890sub is_newer
891{
892        # returns whole stat buffer if newer
893        my $from = shift;
894        my $to = shift;
895        my $touch = shift;
896        my (@from_stat, @to_stat);
897
898        @from_stat = stat($from.$maybedot);
899        if ( $opt_checkdlst ) {
900            my $outtree = expand_macros("%__SRC%");
901            my $commonouttree = expand_macros("%COMMON_OUTDIR%");
902            if ( $from !~ /$outtree/ ) {
903                if ( $from !~ /$commonouttree/ ) {
904                    print_warning("'$from' does not exist") unless -e _;
905                }
906            }
907        }
908        return 0 unless -f _;
909
910        if ( $touch ) {
911            $from_stat[9] = time();
912        }
913        # adjust timestamps to even seconds
914        # this is necessary since NT platforms have a
915        # 2s modified time granularity while the timestamps
916        # on Samba volumes have a 1s granularity
917
918        $from_stat[9]-- if $from_stat[9] % 2;
919
920        if ( $to =~ /^\Q$dest\E/ ) {
921            if ( $from_stat[9] > $logfiledate ) {
922                $logfiledate = $from_stat[9];
923            }
924        } elsif ( $common_build && ( $to =~ /^\Q$common_dest\E/ ) ) {
925            if ( $from_stat[9] > $commonlogfiledate ) {
926                $commonlogfiledate = $from_stat[9];
927            }
928        }
929
930        @to_stat = stat($to.$maybedot);
931        return \@from_stat unless -f _;
932
933        if ( $opt_force ) {
934            return \@from_stat;
935        }
936        else {
937            return ($from_stat[9] > $to_stat[9]) ? \@from_stat : 0;
938        }
939}
940
941sub filter_out
942{
943    my $file = shift;
944
945    foreach my $pattern ( @copy_filter_patterns ) {
946        if  ( $file =~ /$pattern/ ) {
947           print "filter out: $file\n" if $is_debug;
948           return 1;
949        }
950    }
951
952    return 0;
953}
954
955sub fix_file_permissions
956{
957    my $mode = shift;
958    my $file = shift;
959
960    if ( ($mode >> 6) % 2 == 1 ) {
961        $mode = 0777 & ~$umask;
962    }
963    else {
964        $mode = 0666 & ~$umask;
965    }
966    chmod($mode, $file);
967}
968
969sub get_latest_patchlevel
970{
971    # note: feed only well formed library names to this function
972    # of the form libfoo.so.x.y.z with x,y,z numbers
973
974    my @sorted_files = sort by_rev @_;
975    return $sorted_files[-1];
976
977    sub by_rev {
978    # comparison function for sorting
979        my (@field_a, @field_b, $i);
980
981        $a =~ /^(lib[\w-]+(\.so|\.dylib))\.(\d+)\.(\d+)\.(\d+)$/;
982        @field_a = ($3, $4, $5);
983        $b =~ /^(lib[\w-]+(\.so|\.dylib))\.(\d+)\.(\d+)\.(\d+)$/;
984        @field_b = ($3, $4, $5);
985
986        for ($i = 0; $i < 3; $i++)
987          {
988              # if unitialized assign 0 as default value.
989              $field_a[$i] //= 0;
990              $field_b[$i] //= 0;
991              if ( ($field_a[$i] < $field_b[$i]) ) {
992                  return -1;
993              }
994              if ( ($field_a[$i] > $field_b[$i]) ) {
995                  return 1;
996              }
997          }
998
999        # can't happen
1000        return 0;
1001    }
1002
1003}
1004
1005sub push_default_actions
1006{
1007    # any default action (that is an action which must be done even without
1008    # a corresponding d.lst entry) should be pushed here on the
1009    # @action_data list.
1010    my $subdir;
1011    my @subdirs = (
1012                    'bin',
1013                    'doc',
1014                    'inc',
1015                    'lib',
1016                    'par',
1017                    'pck',
1018                    'rdb',
1019                    'res',
1020                    'tmp',
1021                    'xml'
1022                );
1023    push(@subdirs, 'zip') if $opt_zip;
1024    push(@subdirs, 'idl') if ! $common_build;
1025    push(@subdirs, 'pus') if ! $common_build;
1026    my @common_subdirs = (
1027                    'bin',
1028                    'idl',
1029                    'inc',
1030                    'pck',
1031                    'pus',
1032                    'res'
1033                );
1034    push(@common_subdirs, 'zip') if $opt_zip;
1035
1036    if ( ! $opt_delete ) {
1037        # create all the subdirectories on solver
1038        foreach $subdir (@subdirs) {
1039            push(@action_data, ['mkdir', "%_DEST%/$subdir%_EXT%"]);
1040        }
1041        if ( $common_build ) {
1042            foreach $subdir (@common_subdirs) {
1043                push(@action_data, ['mkdir', "%COMMON_DEST%/$subdir%_EXT%"]);
1044            }
1045        }
1046    }
1047    push(@action_data, ['mkdir', "%_DEST%/inc%_EXT%/$module"]);
1048    if ( $common_build ) {
1049        push(@action_data, ['mkdir', "%COMMON_DEST%/inc%_EXT%/$module"]);
1050        push(@action_data, ['mkdir', "%COMMON_DEST%/res%_EXT%/img"]);
1051    } else {
1052        push(@action_data, ['mkdir', "%_DEST%/res%_EXT%/img"]);
1053    }
1054
1055    # deliver build.lst to $dest/inc/$module
1056    push(@action_data, ['copy', "build.lst %_DEST%/inc%_EXT%/$module/build.lst"]);
1057    if ( $common_build ) {
1058        # ... and to $common_dest/inc/$module
1059        push(@action_data, ['copy', "build.lst %COMMON_DEST%/inc%_EXT%/$module/build.lst"]);
1060    }
1061
1062    # need to copy libstaticmxp.dylib for Mac OS X
1063    if ( $^O eq 'darwin' )
1064    {
1065        push(@action_data, ['copy', "../%__SRC%/lib/lib*static*.dylib %_DEST%/lib%_EXT%/lib*static*.dylib"]);
1066    }
1067}
1068
1069sub walk_addincpath_list
1070{
1071    my (@addincpath_headers);
1072    return if $#addincpath_list == -1;
1073
1074    # create hash with all addincpath header names
1075    for (my $i = 0; $i <= $#addincpath_list; $i++) {
1076        my @field = split('/', $addincpath_list[$i][0]);
1077        push (@addincpath_headers, $field[-1]);
1078    }
1079
1080    # now stream all addincpath headers through addincpath filter
1081    for (my $i = 0; $i <= $#addincpath_list; $i++) {
1082        add_incpath_if_newer($addincpath_list[$i][0], $addincpath_list[$i][1], \@addincpath_headers)
1083                ? $files_copied++ : $files_unchanged++;
1084    }
1085}
1086
1087sub add_incpath_if_newer
1088{
1089    my $from = shift;
1090    my $to = shift;
1091    my $modify_headers_ref = shift;
1092    my ($from_stat_ref, $header);
1093
1094    push_on_ziplist($to) if $opt_zip;
1095    push_on_loglist("ADDINCPATH", "$from", "$to") if $opt_log;
1096
1097    if ( $opt_delete ) {
1098        print "REMOVE: $to\n" if $opt_verbose;
1099        my $rc = unlink($to);
1100        return 1 if $rc;
1101        return 0;
1102    }
1103
1104    if ( $from_stat_ref = is_newer($from, $to) ) {
1105        print "ADDINCPATH: $from -> $to\n" if $opt_verbose;
1106
1107        return 1 if $opt_check;
1108
1109        my $save = $/;
1110        undef $/;
1111        open(FROM, "<$from");
1112        # slurp whole file in one big string
1113        my $content = <FROM>;
1114        close(FROM);
1115        $/ = $save;
1116
1117        foreach $header (@$modify_headers_ref) {
1118            $content =~ s/#include [<"]$header[>"]/#include <$module\/$header>/g;
1119        }
1120
1121        open(TO, ">$to");
1122        print TO $content;
1123        close(TO);
1124
1125        utime($$from_stat_ref[9], $$from_stat_ref[9], $to);
1126        fix_file_permissions($$from_stat_ref[2], $to);
1127        return 1;
1128    }
1129    return 0;
1130}
1131
1132sub push_on_ziplist
1133{
1134    my $file = shift;
1135    return if ( $opt_check );
1136    # strip $dest from path since we don't want to record it in zip file
1137    if ( $file =~ s#^\Q$dest\E/##o ) {
1138        if ( $updminor ){
1139            # strip minor from path
1140            my $ext = "%_EXT%";
1141            $ext = expand_macros($ext);
1142            $file =~ s#^$ext##o;
1143        }
1144        push(@zip_list, $file);
1145    } elsif ( $file =~ s#^\Q$common_dest\E/##o ) {
1146        if ( $updminor ){
1147            # strip minor from path
1148            my $ext = "%_EXT%";
1149            $ext = expand_macros($ext);
1150            $file =~ s#^$ext##o;
1151        }
1152        push(@common_zip_list, $file);
1153    }
1154}
1155
1156sub push_on_loglist
1157{
1158    my @entry = @_;
1159    return 0 if ( $opt_check );
1160    return -1 if ( $#entry != 2 );
1161    if (( $entry[0] eq "COPY" ) || ( $entry[0] eq "ADDINCPATH" )) {
1162        return 0 if ( ! -e $entry[1].$maybedot );
1163        # make 'from' relative to source root
1164        $entry[1] = $repository ."/" . $module . "/prj/" . $entry[1];
1165        $entry[1] =~ s/$module\/prj\/\.\./$module/;
1166    }
1167    # platform or common tree?
1168    my $common;
1169    if ( $entry[2] =~ /^\Q$dest\E/ ) {
1170        $common = 0;
1171    } elsif ( $common_build && ( $entry[2] =~ /^\Q$common_dest\E/ )) {
1172        $common = 1;
1173    } else {
1174        warn "Neither common nor platform tree?";
1175        return;
1176    }
1177    # make 'to' relative to SOLARVERSION
1178    my $solarversion  = $ENV{'SOLARVERSION'};
1179    $solarversion =~ s#\\#/#g;
1180    $entry[2] =~ s/^\Q$solarversion\E\///;
1181    # strip minor from 'to'
1182    my $ext = "%_EXT%";
1183    $ext = expand_macros($ext);
1184    $entry[2] =~ s#$ext([\\\/])#$1#o;
1185
1186    if ( $common ) {
1187        push @common_log_list, [@entry];
1188    } else {
1189        push @log_list, [@entry];
1190    }
1191    return 1;
1192}
1193
1194sub zip_files
1195{
1196    my $zipexe = 'zip';
1197    $zipexe .= ' -y' unless  $^O eq 'MSWin32';
1198
1199    my ($platform_zip_file, $common_zip_file);
1200    $platform_zip_file = "%_DEST%/zip%_EXT%/$module.zip";
1201    $platform_zip_file = expand_macros($platform_zip_file);
1202    my (%dest_dir, %list_ref);
1203    $dest_dir{$platform_zip_file} = $dest;
1204    $list_ref{$platform_zip_file} = \@zip_list;
1205    if ( $common_build ) {
1206        $common_zip_file = "%COMMON_DEST%/zip%_EXT%/$module.zip";
1207        $common_zip_file = expand_macros($common_zip_file);
1208        $dest_dir{$common_zip_file}   = $common_dest;
1209        $list_ref{$common_zip_file}   = \@common_zip_list;
1210    }
1211
1212    my $ext = "%_EXT%";
1213    $ext = expand_macros($ext);
1214
1215    my @zipfiles;
1216    $zipfiles[0] = $platform_zip_file;
1217    if ( $common_build ) {
1218        push @zipfiles, ($common_zip_file);
1219    }
1220    foreach my $zip_file ( @zipfiles ) {
1221        print "ZIP: updating $zip_file\n" if $opt_verbose;
1222        next if ( $opt_check );
1223
1224        if ( $opt_delete ) {
1225            if ( -e $zip_file ) {
1226                unlink $zip_file or die "Error: can't remove file '$zip_file': $!";
1227            }
1228            next;
1229        }
1230
1231        local $work_file = "";
1232        if ( $zip_file eq $common_zip_file) {
1233            # Zip file in common tree: work on uniq copy to avoid collisions
1234            $work_file = $zip_file;
1235            $work_file =~ s/\.zip$//;
1236            $work_file .= (sprintf('.%d-%d', $$, time())) . ".zip";
1237            die "Error: temp file $work_file already exists" if ( -e $work_file);
1238            if ( -e $zip_file ) {
1239                if ( -z $zip_file) {
1240                    # sometimes there are files of 0 byte size - remove them
1241                    unlink $zip_file or print_error("can't remove empty file '$zip_file': $!",0);
1242                } else {
1243                    if ( ! copy($zip_file, $work_file)) {
1244                        # give a warning, not an error:
1245                        # we can zip from scratch instead of just updating the old zip file
1246                        print_warning("can't copy'$zip_file' into '$work_file': $!", 0);
1247                        unlink $work_file;
1248                    }
1249                }
1250            }
1251        } else {
1252            # No pre processing necessary, working directly on solver.
1253            $work_file = $zip_file;
1254        }
1255
1256        # zip content has to be relative to $dest_dir
1257        chdir($dest_dir{$zip_file}) or die "Error: cannot chdir into $dest_dir{$zip_file}";
1258        my $this_ref = $list_ref{$zip_file};
1259        open(ZIP, "| $zipexe -q -o -u -@ $work_file") or die "error opening zip file";
1260        foreach $file ( @$this_ref ) {
1261            print "ZIP: adding $file to $zip_file\n" if $is_debug;
1262            print ZIP "$file\n";
1263        }
1264        close(ZIP);
1265        fix_broken_cygwin_created_zips($work_file) if $^O eq "cygwin";
1266
1267        if ( $zip_file eq $common_zip_file) {
1268            # rename work file back
1269            if ( -e $work_file ) {
1270                if ( -e $zip_file) {
1271                    # do some tricks to be fast. otherwise we may disturb other platforms
1272                    # by unlinking a file which just gets copied -> stale file handle.
1273                    my $buffer_file=$work_file . '_rm';
1274                    rename($zip_file, $buffer_file) or warn "Warning: can't rename old zip file '$zip_file': $!";
1275                    if (! rename($work_file, $zip_file)) {
1276                        print_error("can't rename temporary file to $zip_file: $!",0);
1277                        unlink $work_file;
1278                    }
1279                    unlink $buffer_file;
1280                } else {
1281                    if (! rename($work_file, $zip_file)) {
1282                        print_error("can't rename temporary file to $zip_file: $!",0);
1283                        unlink $work_file;
1284                    }
1285                }
1286            }
1287        }
1288    }
1289}
1290
1291sub fix_broken_cygwin_created_zips
1292# add given extension to or strip it from stored path
1293{
1294    require Archive::Zip; import Archive::Zip;
1295    my $zip_file = shift;
1296
1297    $zip = Archive::Zip->new();
1298    unless ( $zip->read($work_file) == AZ_OK ) {
1299        die "Error: can't open zip file '$zip_file' to fix broken cygwin file permissions";
1300    }
1301    my $latest_member_mod_time = 0;
1302    foreach $member ( $zip->members() ) {
1303        my $attributes = $member->unixFileAttributes();
1304        $attributes &= ~0xFE00;
1305        print $member->fileName() . ": " . sprintf("%lo", $attributes) if $is_debug;
1306        $attributes |= 0x10; # add group write permission
1307        print "-> " . sprintf("%lo", $attributes) . "\n" if $is_debug;
1308        $member->unixFileAttributes($attributes);
1309        if ( $latest_member_mod_time < $member->lastModTime() ) {
1310            $latest_member_mod_time = $member->lastModTime();
1311        }
1312    }
1313    die "Error: can't overwrite zip file '$zip_file' for fixing permissions" unless $zip->overwrite() == AZ_OK;
1314    utime($latest_member_mod_time, $latest_member_mod_time, $zip_file);
1315}
1316
1317sub get_tempfilename
1318{
1319    my $temp_dir = shift;
1320    $temp_dir = ( -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP} || '.' )
1321            unless defined($temp_dir);
1322    if ( ! -d $temp_dir ) {
1323        die "no temp directory $temp_dir\n";
1324    }
1325    my $base_name = sprintf( "%d-%di-%d", $$, time(), $tempcounter++ );
1326    return "$temp_dir/$base_name";
1327}
1328
1329sub write_log
1330{
1331    my (%log_file, %file_date);
1332    $log_file{\@log_list} = "%_DEST%/inc%_EXT%/$module/deliver.log";
1333    $log_file{\@common_log_list} = "%COMMON_DEST%/inc%_EXT%/$module/deliver.log";
1334    $file_date{\@log_list} = $logfiledate;
1335    $file_date{\@common_log_list} = $commonlogfiledate;
1336
1337    my @logs = ( \@log_list );
1338    push @logs, ( \@common_log_list ) if ( $common_build );
1339    foreach my $log ( @logs ) {
1340        $log_file{$log} = expand_macros( $log_file{$log} );
1341        if ( $opt_delete ) {
1342            print "LOG: removing $log_file{$log}\n" if $opt_verbose;
1343            next if ( $opt_check );
1344            unlink $log_file{$log};
1345        } else {
1346            print "LOG: writing $log_file{$log}\n" if $opt_verbose;
1347            next if ( $opt_check );
1348            open( LOGFILE, "> $log_file{$log}" ) or warn "Error: could not open log file.";
1349            foreach my $item ( @$log ) {
1350                print LOGFILE "@$item\n";
1351            }
1352            close( LOGFILE );
1353            utime($file_date{$log}, $file_date{$log}, $log_file{$log});
1354        }
1355        push_on_ziplist( $log_file{$log} ) if $opt_zip;
1356    }
1357    return;
1358}
1359
1360sub check_dlst
1361{
1362    my %createddir;
1363    my %destdir;
1364    my %destfile;
1365    # get all checkable actions to perform
1366    foreach my $action ( @action_data ) {
1367        my $path = expand_macros( $$action[1] );
1368        if ( $$action[0] eq 'mkdir' ) {
1369            $createddir{$path} ++;
1370        } elsif (( $$action[0] eq 'copy' ) || ( $$action[0] eq 'addincpath' )) {
1371            my ($from, $to) = split(' ', $path);
1372            my ($to_fname, $to_dir);
1373            my $withwildcard = 0;
1374            if ( $from =~ /[\*\?\[\]]/ ) {
1375                $withwildcard = 1;
1376            }
1377            ($to_fname, $to_dir) = fileparse($to);
1378            if ( $withwildcard ) {
1379                if ( $to !~ /[\*\?\[\]]/ ) {
1380                    $to_dir = $to;
1381                    $to_fname ='';
1382                }
1383            }
1384            $to_dir =~ s/[\\\/\s]$//;
1385            $destdir{$to_dir} ++;
1386            # Check: copy into non existing directory?
1387            if ( ! $createddir{$to_dir} ) {
1388                # unfortunately it is not so easy: it's OK if a subdirectory of $to_dir
1389                # gets created, because mkpath creates the whole tree
1390                foreach my $directory ( keys %createddir ) {
1391                    if ( $directory =~ /^\Q$to_dir\E[\\\/]/ ) {
1392                        $createddir{$to_dir} ++;
1393                        last;
1394                    }
1395                }
1396                print_warning("Possibly copying into directory without creating in before: '$to_dir'")
1397                    unless $createddir{$to_dir};
1398            }
1399            # Check: overwrite file?
1400            if ( ! $to ) {
1401                if ( $destfile{$to} ) {
1402                    print_warning("Multiple entries copying to '$to'");
1403                }
1404                $destfile{$to} ++;
1405            }
1406        }
1407    }
1408}
1409
1410sub cleanup
1411{
1412    # remove empty directories
1413    foreach my $path ( @dirlist ) {
1414        $path = expand_macros($path);
1415        if ( $opt_check ) {
1416            print "RMDIR: $path\n" if $opt_verbose;
1417        } else {
1418            rmdir $path;
1419        }
1420    }
1421}
1422
1423sub delete_output
1424{
1425    my $output_path = expand_macros("../%__SRC%");
1426    if ( "$output_path" ne "../" ) {
1427        if ( rmtree([$output_path], 0, 1) ) {
1428            print "Deleted output tree.\n" if $opt_verbose;
1429        }
1430        else {
1431            print_error("Error deleting output tree $output_path: $!",0);
1432        }
1433    }
1434    else {
1435        print_error("Output not deleted - INPATH is not set");
1436    }
1437}
1438
1439sub print_warning
1440{
1441    my $message = shift;
1442    my $line = shift;
1443
1444    print STDERR "$script_name: ";
1445    if ( $dlst_file ) {
1446        print STDERR "$dlst_file: ";
1447    }
1448    if ( $line ) {
1449        print STDERR "line $line: ";
1450    }
1451    print STDERR "WARNING: $message\n";
1452}
1453
1454sub print_error
1455{
1456    my $message = shift;
1457    my $line = shift;
1458
1459    print STDERR "$script_name: ";
1460    if ( $dlst_file ) {
1461        print STDERR "$dlst_file: ";
1462    }
1463    if ( $line ) {
1464        print STDERR "line $line: ";
1465    }
1466    print STDERR "ERROR: $message\n";
1467    $error ++;
1468}
1469
1470sub print_stats
1471{
1472    print "Module '$module' delivered ";
1473    if ( $error ) {
1474        print "with errors\n";
1475    } else {
1476        print "successfully.";
1477        if ( $opt_delete ) {
1478            print " $files_copied files removed,";
1479        }
1480        else {
1481            print " $files_copied files copied,";
1482        }
1483        print " $files_unchanged files unchanged\n";
1484    }
1485}
1486
1487sub cleanup_and_die
1488{
1489    # clean up on unexpected termination
1490    my $sig = shift;
1491    if ( defined($temp_file) && -e $temp_file ) {
1492        unlink($temp_file);
1493    }
1494    if ( defined($work_file) && -e $work_file ) {
1495        unlink($work_file);
1496        print STDERR "$work_file removed\n";
1497    }
1498
1499    die "caught unexpected signal $sig, terminating ...";
1500}
1501
1502sub usage
1503{
1504    my $exit_code = shift;
1505    print STDERR "Usage:\ndeliver [OPTIONS] [DESTINATION-PATH]\n";
1506    print STDERR "Options:\n";
1507    print STDERR "  -check       just print what would happen, no actual copying of files\n";
1508    print STDERR "  -checkdlst   be verbose about (possible) d.lst bugs\n";
1509    print STDERR "  -delete      delete files (undeliver), use with care\n";
1510    print STDERR "  -deloutput   remove the output tree after copying\n";
1511    print STDERR "  -dontdeletecommon do not delete common files (for -delete option)\n";
1512    print STDERR "  -force       copy even if not newer\n";
1513    print STDERR "  -help        print this message\n";
1514    if ( !defined($ENV{GUI}) || $ENV{GUI} ne 'WNT' ) {
1515        print STDERR "  -link        hard link files into the solver to save disk space\n";
1516    }
1517    print STDERR "  -quiet       be quiet, only report errors\n";
1518    print STDERR "  -verbose     be verbose\n";
1519    print STDERR "  -zip         additionally create zip files of delivered content\n";
1520    print STDERR "Options '-zip' and a destination-path are mutually exclusive.\n";
1521    print STDERR "Options '-check' and '-quiet' are mutually exclusive.\n";
1522    exit($exit_code);
1523}
1524
1525# vim: set ts=4 shiftwidth=4 expandtab syntax=perl:
1526