Subversion Repositories DevTools

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
407 dpurdie 1
########################################################################
3921 dpurdie 2
# Copyright (C) 1998-2013 Vix Technology, All rights reserved
407 dpurdie 3
#
3921 dpurdie 4
# Module name   : DebianPackager.pl
407 dpurdie 5
# Module type   : Makefile system
3921 dpurdie 6
# Compiler(s)   : Perl
407 dpurdie 7
# Environment(s): jats
8
#
9
# Description   : This program is invoked by the MakeDebianPackage
10
#                 directive, that is a part of this package
11
#
12
#                 The program will use a user-provided script in order
13
#                 to create a Debian Package.
14
#
15
#                 The user script may call a number of directives in order to
16
#                 construct an image of the package being installed.
17
#
18
#                 The script specifies Debian configuration scaripts that
19
#                 will be embedded in the package.
20
#
21
#                 This program will:
22
#                   Construct a filesystem image under control of the directives
23
#                   within the user script
24
#
25
#                   Massage the Debian control file
26
#
27
#                   Create a Debian Package
28
#
29
#                   Transfer it to the users 'BIN' directory, where it is
30
#                   available to be packaged.
31
#
32
#                 Summary of directives available to the user-script:
33
#                       AddInitScript           - Add an init script
34
#                       CatFile                 - Append to a file
4641 dpurdie 35
#                       ConvertFile             - Convert file(s) to Unix or Dos Text
407 dpurdie 36
#                       CopyDir                 - Copy directory tree
37
#                       CopyFile                - Copy a file
38
#                       CopyBinFile             - Copy an executable file
39
#                       CopyLibFile             - Copy a library file
40
#                       CreateDir               - Create a directory
41
#                       DebianFiles             - Specify control and script files
4636 dpurdie 42
#                       DebianControlFile       - Specify control and script files
43
#                       DebianDepends           - Add Depends entry to control file
407 dpurdie 44
#                       EchoFile                - Place text into a file
45
#                       MakeSymLink             - Create a symbolic link
46
#                       PackageDescription      - Specify the package description
4641 dpurdie 47
#                       ReplaceTags             - Replace Tags on target file
407 dpurdie 48
#                       SetFilePerms            - Set file permissions
49
#                       SetVerbose              - Control progress display
50
#                       IsProduct               - Flow control
51
#                       IsPlatform              - Flow control
52
#                       IsTarget                - Flow control
427 dpurdie 53
#                       IsVariant               - Flow control
407 dpurdie 54
#
55
#                 Thoughts for expansion:
56
#                       SrcDir                  - Extend path for resolving local files
57
#
58
#                   Less used:
59
#                        ExpandLinkFiles        - Expand .LINK files
60
#
61
#                   Internal Use:
62
#                        FindFiles              - Find a file
63
#                        ResolveFile            - Resolve a 'local' source file
4641 dpurdie 64
#                        chmodItem              - Set file or directory permissions
407 dpurdie 65
#                        
66
#......................................................................#
67
 
411 dpurdie 68
require 5.006_001;
407 dpurdie 69
use strict;
70
use warnings;
71
 
72
use Getopt::Long;
73
use File::Path;
74
use File::Copy;
75
use File::Find;
76
use JatsSystem;
77
use FileUtils;
78
use JatsError;
4636 dpurdie 79
use JatsLocateFiles;
407 dpurdie 80
use ReadBuildConfig;
423 dpurdie 81
use JatsCopy ();                            # Don't import anything
407 dpurdie 82
 
83
#
84
#   Globals
85
#
425 dpurdie 86
my $DebianWorkDirBase;                      # Workspace
407 dpurdie 87
my $DebianWorkDir;                          # Dir to create file system image within
88
 
89
#
90
#   Command line options
91
#
92
my $opt_debug   = $ENV{'GBE_DEBUG'};        # Allow global debug
93
my $opt_verbose = $ENV{'GBE_VERBOSE'};      # Allow global verbose
94
my $opt_vargs;                              # Verbose arg
95
my $opt_help = 0;
96
my $opt_manual = 0;
97
my $opt_clean = 0;
98
my $opt_platform;
99
my $opt_type;
100
my $opt_buildname;
101
my $opt_buildversion;
102
my $opt_interfacedir;
103
my $opt_target;
104
my $opt_product;
105
my $opt_package_script;
106
my $opt_interfaceincdir;
107
my $opt_interfacelibdir;
108
my $opt_interfacebindir;
109
my $opt_libdir;
110
my $opt_bindir;
111
my $opt_localincdir;
112
my $opt_locallibdir;
113
my $opt_localbindir;
114
my $opt_pkgdir;
115
my $opt_pkglibdir;
116
my $opt_pkgbindir;
117
my $opt_pkgpkgdir;
118
my $opt_output;
417 dpurdie 119
my $opt_name;
427 dpurdie 120
my $opt_variant;
3921 dpurdie 121
my $opt_pkgarch;
407 dpurdie 122
 
123
#
124
#   Options derived from script directives
125
#
126
my $opt_description;
127
 
415 dpurdie 128
#
129
#   Globals
130
#
131
my @ResolveFileList;                    # Cached Package File List
132
my @ResolveBinFileList;                 # Cached PackageBin File List
133
my @ResolveLibFileList;                 # Cached PackageLib File List
4635 dpurdie 134
my %DebianControlFiles;                 # Control Files
135
my %DebianControlFileNames;             # Control Files by name
136
my @DependencyList;                     # Package Dependencies
4666 dpurdie 137
my @ConfigList;                         # Config Files
407 dpurdie 138
 
139
#-------------------------------------------------------------------------------
140
# Function        : Main Entry point
141
#
142
# Description     : This function will be called when the package is initialised
143
#                   Extract arguments from the users environment
144
#
145
#                   Done here to greatly simplify the user script
146
#                   There should be no junk in the user script - keep it simple
147
#
148
# Inputs          :
149
#
150
# Returns         : 
151
#
152
main();
153
sub main
154
{
155
    my $result = GetOptions (
156
                "verbose:s"         => \$opt_vargs,
157
                "clean"             => \$opt_clean,
158
                "Type=s"            => \$opt_type,
4105 dpurdie 159
                "BuildName=s"       => \$opt_buildname,                     # Raw Jats Package Name (Do not use)
160
                "Name=s"            => \$opt_name,                          # Massaged Debian Package Name
407 dpurdie 161
                "BuildVersion=s"    => \$opt_buildversion,
162
                "Platform=s"        => \$opt_platform,
163
                "Target=s"          => \$opt_target,
164
                "Product=s"         => \$opt_product,
165
                "DebianPackage=s"   => \$opt_package_script,
166
                "InterfaceDir=s"    => \$opt_interfacedir,
167
                "InterfaceIncDir=s" => \$opt_interfaceincdir,
168
                "InterfaceLibDir=s" => \$opt_interfacelibdir,
169
                "InterfaceBinDir=s" => \$opt_interfacebindir,
170
                "LibDir=s"          => \$opt_libdir,
171
                "BinDir=s"          => \$opt_bindir,
172
                "LocalIncDir=s"     => \$opt_localincdir,
173
                "LocalLibDir=s"     => \$opt_locallibdir,
174
                "LocalBinDir=s"     => \$opt_localbindir,
175
                "PackageDir=s"      => \$opt_pkgdir,
176
                "PackageLibDir=s"   => \$opt_pkglibdir,
177
                "PackageBinDir=s"   => \$opt_pkgbindir,
178
                "PackagePkgDir=s"   => \$opt_pkgpkgdir,
179
                "Output=s"          => \$opt_output,
427 dpurdie 180
                "Variant:s"         => \$opt_variant,
3921 dpurdie 181
                "PkgArch:s"         => \$opt_pkgarch,
407 dpurdie 182
    );
183
    $opt_verbose++ unless ( $opt_vargs eq '@' );
184
 
185
    ErrorConfig( 'name'    => 'DebianUtils',
186
                 'verbose' => $opt_verbose,
187
                 'debug'   => $opt_debug );
188
 
189
    #
190
    #   Init the FileSystem Uiltity interface
191
    #
192
    InitFileUtils();
193
 
194
    #
195
    #   Ensure that we have all required options
196
    #
197
    Error ("Platform not set")                  unless ( $opt_platform );
198
    Error ("Type not set")                      unless ( $opt_type );
199
    Error ("BuildName not set")                 unless ( $opt_buildname );
4105 dpurdie 200
    Error ("Debian Package Name not set")       unless ( $opt_name );
407 dpurdie 201
    Error ("BuildVersion not set")              unless ( $opt_buildversion );
202
    Error ("InterfaceDir not set")              unless ( $opt_interfacedir );
203
    Error ("Target not set")                    unless ( $opt_target );
204
    Error ("Product not set")                   unless ( $opt_product );
205
    Error ("DebianPackage not set")             unless ( $opt_package_script );
206
    Error ("Ouput File not set")                unless ( $opt_output );
207
 
208
    #
209
    #   Read in relevent config information
210
    #
211
    ReadBuildConfig ($opt_interfacedir, $opt_platform, '--NoTest' );
212
 
213
    #
214
    #   Build the package image in a directory based on the target being created
215
    #
425 dpurdie 216
    $DebianWorkDirBase = "$opt_platform$opt_type.image";
217
    $DebianWorkDir = "$DebianWorkDirBase/$opt_name";
407 dpurdie 218
 
219
    #
220
    #   Configure the System command to fail on any error
221
    #
222
    SystemConfig ( ExitOnError => 1 );
223
 
224
    #
225
    #   Extract the 'name' of the package from the output path
226
    #   Display purposes only
227
    #
228
    my $DebianPkgName = StripDirExt($opt_output);
229
 
230
    #
231
    #   Display variables used
232
    #
233
    Message    "=Building Debian Package =============================================";
417 dpurdie 234
    Message    "Build $opt_name";
407 dpurdie 235
    Message    "       Package: $opt_buildname";
427 dpurdie 236
    Message    "       Variant: $opt_variant" if ($opt_variant);
407 dpurdie 237
    Message    "       Version: $opt_buildversion";
238
    Message    "  Building for: $opt_platform, $opt_target";
239
    Message    "       Product: $opt_product";
240
    Message    "          Type: $opt_type";
3921 dpurdie 241
    Message    "      Pkg Arch: $opt_pkgarch" if ($opt_pkgarch);
407 dpurdie 242
    Verbose    "       Verbose: $opt_verbose";
243
    Verbose    "  InterfaceDir: $opt_interfacedir";
244
    Message    "       Package: $DebianPkgName";
245
    Message    "======================================================================";
246
 
247
    #
3921 dpurdie 248
    #   Defaults
249
    #
250
    $opt_pkgarch = $opt_platform unless ( $opt_pkgarch );
251
 
252
    #
407 dpurdie 253
    #   Perform Clean up
254
    #   Invoked during "make clean" or "make clobber"
255
    #
256
    if ( $opt_clean )
257
    {
258
        Message ("Remove packaging directory: $DebianWorkDir");
425 dpurdie 259
 
260
        #
261
        #   Remove the directory for this package
262
        #   Remove the general work dir - if all packages have been cleaned
263
        #
407 dpurdie 264
        rmtree( $DebianWorkDir );
425 dpurdie 265
        rmdir( $DebianWorkDirBase );
407 dpurdie 266
        rmtree ($opt_output) if ( -f $opt_output );
267
        exit;
268
    }
269
 
270
    #
271
    #   Clean  out the WORK directory
272
    #   Always start with a clean slate
273
    #
274
    #   Ensure that the base of the directory tree does not have 'setgid'
275
    #       This will upset the debian packager
276
    #       This may be an artifact from the users directory and not expected
277
    #
278
    rmtree( $DebianWorkDir );
279
    mkpath( $DebianWorkDir );
280
 
281
    my $perm = (stat $DebianWorkDir)[2] & 0777;
282
    chmod ( $perm & 0777, $DebianWorkDir );
283
 
284
    #
285
    #   Invoke the user script to do the hard work
286
    #
4139 dpurdie 287
    unless (my $return = do $opt_package_script) {
288
            Error ("Couldn't parse $opt_package_script: $@") if $@;
289
            Error ("Couldn't do $opt_package_script: $!")    unless defined $return;
290
        }
407 dpurdie 291
 
292
    #
293
    #   Complete the building of the package
294
    #
295
    BuildDebianPackage ();
296
    Message ("Created Debian Package");
297
}
298
 
299
#-------------------------------------------------------------------------------
300
# Function        : BuildDebianPackage
301
#
302
# Description     : This function will create the Debian Package
303
#                   and transfer it to the target directory
304
#
305
# Inputs          : None
306
#
307
# Returns         : Nothing
308
#
309
sub BuildDebianPackage
310
{
311
    Error ("BuildDebianPackage: No Control File or Package Description")
4635 dpurdie 312
        unless ( exists($DebianControlFiles{'control'}) || $opt_description );
407 dpurdie 313
 
314
    #
315
    #   Convert the FileSystem Image into a Debian Package
316
    #       Insert Debian control files
317
    #
318
    Verbose ("Copy in the Debian Control Files");
319
    mkdir ( "$DebianWorkDir/DEBIAN" );
320
 
4635 dpurdie 321
    #
322
    #   Copy in all the named Debian Control files
323
    #       Ignore any control file. It will be done next
324
    #
325
    foreach my $key ( keys %DebianControlFiles )
326
    {
327
        next if ($key eq 'control');
328
        CopyFile ( $DebianControlFiles{$key},    "/DEBIAN", $key );
329
    }
4666 dpurdie 330
 
331
    #
332
    #   Create 'conffiles'
333
    #       Append to any user provided file
334
    if ( @ConfigList )
335
    {
336
        my $conffiles = "$DebianWorkDir/DEBIAN/conffiles";
337
        Warning("Appending user specified entries to conffiles") if ( -f $conffiles);
338
        FileAppend( $conffiles, @ConfigList );
339
    }
4635 dpurdie 340
 
341
    #
342
    #   Massage the 'control' file
343
    #
344
    UpdateControlFile ($DebianControlFiles{'control'} );
407 dpurdie 345
 
4635 dpurdie 346
    #
347
    #   Mark all files in the debian folder as read-execute
348
    #
407 dpurdie 349
    System ( 'chmod', '-R', 'a+rx', "$DebianWorkDir/DEBIAN" );
350
    System ( 'build_dpkg.sh', '-b', $DebianWorkDir);
351
    System ( 'mv', '-f', "$DebianWorkDir.deb", $opt_output );
352
 
353
    System ("build_dpkg.sh", '-I', $opt_output) if (IsVerbose(1));
354
 
355
}
356
 
357
#-------------------------------------------------------------------------------
358
# Function        : UpdateControlFile
359
#
4188 dpurdie 360
# Description     : Update the Debian 'control' file to fix up various fields
407 dpurdie 361
#                   within the file.
362
#
363
#                   If the files has not been specified, then a basic control
364
#                   file will be provided.
365
#
366
#                   This routine knows where the control file will be placed
367
#                   within the output work space.
368
#
369
# Inputs          : $src            - Path to source file
370
#                   Uses global variables
371
#
372
# Returns         : Nothing
373
#
374
sub UpdateControlFile
375
{
376
    my($src) = @_;
377
    my $dst = "$DebianWorkDir/DEBIAN/control";
378
 
379
    unless ( $src )
380
    {
381
        CreateControlFile();
382
        return;
383
    }
384
 
4635 dpurdie 385
    #
386
    #   User has provided a control file
387
    #       Tweak the internals
388
    #
407 dpurdie 389
    Verbose ("UpdateControlFile: $dst" );
390
    $src = ResolveFile( 0, $src );
391
 
4635 dpurdie 392
    #   Calc depends line
4636 dpurdie 393
    my $depData = join (', ', @DependencyList );
4635 dpurdie 394
 
395
    open (SF, '<', $src) || Error ("UpdateControlFile: Cannot open:$src, $!");
396
    open (DF, '>', $dst) || Error ("UpdateControlFile: Cannot create:$dst, $!");
407 dpurdie 397
    while ( <SF> )
398
    {
399
        s~\s*$~~;
400
        if ( m~^Package:~ ) {
4105 dpurdie 401
            $_ = "Package: $opt_name";
407 dpurdie 402
 
403
        } elsif ( m~^Version:~ ) {
404
            $_ = "Version: $opt_buildversion";
405
 
406
        } elsif ( m~^Architecture:~ ) {
3921 dpurdie 407
            $_ = "Architecture: $opt_pkgarch";
407 dpurdie 408
 
409
        } elsif ( $opt_description && m~^Description:~ ) {
410
            $_ = "Description: $opt_description";
4635 dpurdie 411
 
412
        } elsif ( m~^Depends:~ ) {
413
            $_ = "Depends: $depData";
414
            $depData = '';
407 dpurdie 415
        }
416
        print DF $_ , "\n";
417
    }
4635 dpurdie 418
 
407 dpurdie 419
    close (SF);
420
    close (DF);
4635 dpurdie 421
 
422
    #
423
    #   Warn if Depends section is needed
424
    #
425
    Error ("No Depends section seen in user control file") 
426
        if ($depData);
407 dpurdie 427
}
428
 
429
#-------------------------------------------------------------------------------
430
# Function        : CreateControlFile
431
#
432
# Description     : Craete a basic debian control file
433
#
434
# Inputs          : Uses global variables
435
#
436
# Returns         : 
437
#
438
sub CreateControlFile
439
{
440
    my $dst = "$DebianWorkDir/DEBIAN/control";
441
 
442
    Verbose ("CreateControlFile: $dst" );
443
 
4636 dpurdie 444
    my $depData = join (', ', @DependencyList );
4635 dpurdie 445
 
407 dpurdie 446
    open (DF, '>', $dst) || Error ("CreateControlFile: Cannot create:$dst");
4105 dpurdie 447
    print DF "Package: $opt_name\n";
407 dpurdie 448
    print DF "Version: $opt_buildversion\n";
449
    print DF "Section: main\n";
450
    print DF "Priority: standard\n";
3921 dpurdie 451
    print DF "Architecture: $opt_pkgarch\n";
452
    print DF "Essential: No\n";
453
    print DF "Maintainer: Vix Technology\n";
407 dpurdie 454
    print DF "Description: $opt_description\n";
4635 dpurdie 455
    print DF "Depends: $depData\n" if ($depData);
456
 
407 dpurdie 457
    close (DF);
458
}
459
 
460
#-------------------------------------------------------------------------------
461
# Function        : SetVerbose
462
#
463
# Description     : Set the level of verbosity
464
#                   Display activity
465
#
466
# Inputs          : Verbosity level
467
#                       0 - Use makefile verbosity (Default)
468
#                       1..2
469
#
470
# Returns         : 
471
#
472
sub SetVerbose
473
{
474
    my ($level) = @_;
475
 
476
    $level = $opt_verbose unless ( $level );
477
    $opt_verbose = $level;
478
    ErrorConfig( 'verbose' => $level);
479
}
480
 
481
 
482
#-------------------------------------------------------------------------------
483
# Function        : DebianFiles
484
#
485
# Description     : Name Debian builder control files
486
#                   May be called multiple times
487
#
488
# Inputs          : Options
489
#                       --Control=file
490
#                       --PreRm=file
491
#                       --PostRm=file
492
#                       --PreInst=file
493
#                       --PostInst=file
4635 dpurdie 494
#                         
407 dpurdie 495
#
496
# Returns         : Nothing
497
#
498
sub DebianFiles
499
{
500
    #
4635 dpurdie 501
    #   Extract names
407 dpurdie 502
    #
503
    Verbose ("Specify Debian Control Files and Scripts");
504
    foreach  ( @_ )
505
    {
4635 dpurdie 506
        if ( m/^--Control=(.+)/i ) {
507
            DebianControlFile('control',$1)
407 dpurdie 508
 
4635 dpurdie 509
        } elsif ( m/^--PreRm=(.+)/i ) {
510
            DebianControlFile('prerm',$1)
407 dpurdie 511
 
4635 dpurdie 512
        } elsif ( m/^--PostRm=(.+)/i ) {
513
            DebianControlFile('postrm',$1)
407 dpurdie 514
 
4635 dpurdie 515
        } elsif ( m/^--PreInst=(.+)/i ) {
516
            DebianControlFile('preinst',$1)
407 dpurdie 517
 
4635 dpurdie 518
        } elsif ( m/^--PostInst=(.+)/i ) {
519
            DebianControlFile('postinst',$1)
407 dpurdie 520
 
521
        } else {
522
            Error ("DebianFiles: Unknown option: $_");
523
        }
524
    }
525
}
526
 
527
#-------------------------------------------------------------------------------
4635 dpurdie 528
# Function        : DebianControlFile 
529
#
530
# Description     : Add special control files to the Debian Installer 
531
#                   Not useful for embedded installers
532
#
533
#                   More general than DebianFiles()
534
#
535
# Inputs          : name            - Target Name
536
#                                     If the name starts with 'package.' then it will be replaced
537
#                                     with the name of the current package
538
#                   file            - Source File Name
539
#
540
# Returns         : 
541
#
542
sub DebianControlFile
543
{
544
    my ($name, $file, $misc) = @_;
545
    Error ("DebianControlFile: Unknown argument: $misc") if defined $misc;
546
 
547
    #
548
    #   Some control files need to have the package name prepended
549
    #
550
    $name =~ s~^package\.~$opt_name.~;
551
 
552
    #
553
    #   Only allow one file of each type
554
    #       Try to protect the user by testing for names by lowercase
555
    #
556
    my $simpleName = lc($name);
557
    Error("DebianControlFile: Multiple definitions for '$name' not allowed")
558
        if (exists $DebianControlFileNames{$simpleName});
559
 
560
    Error("DebianControlFile: $name. File not found", "Control target: $name", "File not found: $file")
561
        unless (-f $file);
562
 
563
    #
564
    #   Add info to data structures
565
    #
566
    $DebianControlFiles{$name} = $file;
567
    $DebianControlFileNames{$simpleName} = $name;
568
}
569
 
570
#-------------------------------------------------------------------------------
571
# Function        : DebianDepends 
572
#
573
# Description     : This directive allows simple dependency information to be  
574
#                   inserted into the control file
575
#
4636 dpurdie 576
#                   Not useful in embedded system
4635 dpurdie 577
#
578
# Inputs          : Entry             - A dependency entry
579
#                   ...               - More entries
580
#                   
581
#
582
# Returns         : Nothing
583
#
584
sub DebianDepends
585
{
586
    push @DependencyList, @_;
587
}
588
 
589
 
590
#-------------------------------------------------------------------------------
407 dpurdie 591
# Function        : PackageDescription
592
#
593
# Description     : Specify the Package Description
594
#                   Keep it short
595
#
596
# Inputs          : $description
597
#
598
# Returns         : 
599
#
600
sub PackageDescription
601
{
602
    ($opt_description) = @_;
603
}
604
 
605
#-------------------------------------------------------------------------------
606
# Function        : MakeSymLink
607
#
608
# Description     : Create a symlink - with error detection
609
#
610
# Inputs          : old_file    - Link Target
611
#                                 Path to the link target
612
#                                 If an ABS path is provided, the routine will
613
#                                 attempt to create a relative link.
614
#                   new_file    - Relative to the output work space
615
#                                 Path to where the 'link' file will be created
616
#                   Options     - Must be last
617
#                                 --NoClean         - Don't play with links
618
#                                 --NoDotDot        - Don't create symlinks with ..
619
#
620
# Returns         : Nothing
621
#
622
sub MakeSymLink
623
{
624
    my $no_clean;
625
    my $no_dot;
626
    my @args;
627
 
628
    #
629
    #   Extract options
630
    #
631
    foreach ( @_ )
632
    {
633
        if ( m/^--NoClean/i ) {
634
            $no_clean = 1;
635
 
636
        } elsif ( m/^--NoDotDot/i ) {
637
            $no_dot = 1;
638
 
639
        } elsif ( m/^--/ ) {
640
            Error ("MakeSymLink: Unknown option: $_");
641
 
642
        } else {
643
            push @args, $_;
644
        }
645
    }
646
 
647
    my ($old_file, $new_file) = @args;
648
 
649
    my $tfile = $DebianWorkDir . '/' . $new_file;
650
    $tfile =~ s~//~/~;
651
    Verbose ("Symlink $old_file -> $new_file" );
652
 
653
    #
654
    #   Create the directory in which the link will be placed
655
    #   Remove any existing file of the same name
656
    #
657
    my $dir = StripFileExt( $tfile );
658
    mkpath( $dir) unless -d $dir;
659
    unlink $tfile;
660
 
661
    #
662
    #   Determine a good name of the link
663
    #   Convert to a relative link in an attempt to prune them
664
    #
665
    my $sfile = $old_file;
666
    unless ( $no_clean )
667
    {
668
        $sfile = CalcRelPath( StripFileExt( $new_file ), $old_file );
669
        $sfile = $old_file if ( $no_dot && $sfile =~ m~^../~ );
670
    }
671
 
672
    my $result = symlink $sfile, $tfile;
673
    Error ("Cannot create symlink. $old_file -> $new_file") unless ( $result );
674
}
675
 
676
#-------------------------------------------------------------------------------
677
# Function        : CopyFile
678
#
679
# Description     : Copy a file to a target dir
680
#                   Used for text files, or files with fixed names
681
#
682
# Inputs          : $src
683
#                   $dst_dir    - Within the output workspace
684
#                   $dst_name   - Output Name [Optional]
685
#                   Options     - Common Copy Options
686
#
687
# Returns         : Full path to destination file
688
#
689
sub CopyFile
690
{
691
    CopyFileCommon( \&ResolveFile, @_ );
692
}
693
 
694
#-------------------------------------------------------------------------------
695
# Function        : CopyBinFile
696
#
697
# Description     : Copy a file to a target dir
698
#                   Used for executable programs. Will look in places where
699
#                   programs are stored.
700
#
701
# Inputs          : $src
702
#                   $dst_dir    - Within the output workspace
703
#                   $dst_name   - Output Name [Optional]
704
#
705
#                   Options:
706
#                       --FromPackage
707
#                       --SoftLink=xxxx
708
#                       --LinkFile=xxxx
709
#
710
#
711
# Returns         : Full path to destination file
712
#
713
sub CopyBinFile
714
{
715
    CopyFileCommon( \&ResolveBinFile, @_ );
716
}
717
 
718
#-------------------------------------------------------------------------------
719
# Function        : CopyLibFile
720
#
721
# Description     : Copy a file to a target dir
722
#                   Used for shared programs. Will look in places where
723
#                   shared libraries are stored.
724
#
725
# Inputs          : $src        - Base for 'realname' (no lib, no extension)
726
#                   $dst_dir    - Within the output workspace
727
#                   $dst_name   - Output Name [Optional, but not suggested]
728
#
729
# Returns         : Full path to destination file
730
#
731
# Notes           : Copying 'lib' files
732
#                   These are 'shared libaries. There is no provision for copying
733
#                   static libraries.
734
#
735
#                   The tool will attempt to copy a well-formed 'realname' library
736
#                   The soname of the library should be constructed on the target
737
#                   platform using ldconfig.
738
#                   There is no provision to copy the 'linker' name
739
#
740
#                   Given a request to copy a library called 'fred', then the
741
#                   well formed 'realname' will be:
742
#                           libfred[P|D|]].so.nnnnn
743
#                   where:
744
#                           nnnn is the library version
745
#                           [P|D|] indicates Production, Debug or None
746
#
747
#                   The 'soname' is held within the realname form of the library
748
#                   and will be created by lsconfig.
749
#
750
#                   The 'linkername' would be libfred[P|D|].so. This is only
751
#                   needed when linking against the library.
752
#
753
#
754
#                   The routine will also recognize Windows DLLs
755
#                   These are of the form fred[P|D|].nnnnn.dll
756
#
757
sub CopyLibFile
758
{
759
    CopyFileCommon( \&ResolveLibFile, @_ );
760
}
761
 
762
#-------------------------------------------------------------------------------
763
# Function        : CopyFileCommon
764
#
765
# Description     : Common ( internal File Copy )
766
#
767
# Inputs          : $resolver           - Ref to function to resolve source file
768
#                   $src                - Source File Name
769
#                   $dst_dir            - Target Dir
770
#                   $dst_name           - Target Name (optional)
771
#                   Options
772
#                   Options:
773
#                       --FromPackage
774
#                       --SoftLink=xxxx
775
#                       --LinkFile=xxxx
4666 dpurdie 776
#                       --ConfigFile
407 dpurdie 777
#
778
# Returns         : 
779
#
780
sub CopyFileCommon
781
{
782
    my $from_package = 0;
783
    my $isa_linkfile = 0;
4666 dpurdie 784
    my $isa_configFile = 0;
407 dpurdie 785
    my @llist;
786
    my @args;
787
 
788
    #
789
    #   Parse options
790
    #
791
    foreach ( @_ )
792
    {
793
        if ( m/^--FromPackage/ ) {
794
            $from_package = 1;
795
 
796
        } elsif ( m/^--LinkFile/ ) {
797
            $isa_linkfile = 1;
798
 
4666 dpurdie 799
        } elsif ( m/^--ConfFile/i ) {
800
            $isa_configFile = 1;
801
 
407 dpurdie 802
        } elsif ( m/^--SoftLink=(.+)/ ) {
803
            push @llist, $1;
804
 
805
        } elsif ( m/^--/ ) {
806
            Error ("FileCopy: Unknown option: $_");
807
 
808
        } else {
809
            push @args, $_;
810
        }
811
    }
812
 
813
    #
814
    #   Extract non-options.
815
    #   These are the bits that are left over
816
    #
817
    my ($resolver, $src, $dst_dir, $dst_name ) = @args;
818
 
819
    #
820
    #   Clean up dest_dir. Must start with a / and not end with one
821
    #
822
    $dst_dir = "/$dst_dir/";
823
    $dst_dir =~ s~/+~/~g;
824
    $dst_dir =~ s~/$~~;
825
 
826
    Verbose ("CopyFile: $src, $dst_dir, " . ($dst_name || ''));
827
    foreach $src ( &$resolver( $from_package, $src ) )
828
    {
829
        my $dst_fname = $dst_name ? $dst_name : StripDir($src);
830
        my $dst_file = "$dst_dir/$dst_fname";
831
        Verbose ("CopyFile: Copy $src, $dst_file" );
832
 
833
 
834
        #
835
        #   LinkFiles are special
836
        #   They get concatenated to any existing LINKS File
837
        #
838
        if ( $isa_linkfile )
839
        {
840
            CatFile ( $src, "$dst_dir/.LINKS" );
841
        }
842
        else
843
        {
844
            mkpath( "$DebianWorkDir$dst_dir", 0, 0775);
845
            unlink ("$DebianWorkDir$dst_file");
846
            System ('cp','-f', $src, "$DebianWorkDir$dst_file" );
847
 
848
            foreach my $lname ( @llist )
849
            {
850
                $lname = $dst_dir . '/' . $lname unless ( $lname =~ m ~^/~ );
851
                MakeSymLink( $dst_file ,$lname);
852
            }
853
        }
4666 dpurdie 854
 
855
        #
856
        #   ConfigFiles are marked so that they can be handled by the debain installer
857
        #
858
        if ($isa_configFile)
859
        {
860
            push @ConfigList, $dst_file;
861
        }
407 dpurdie 862
    }
863
}
864
 
865
#-------------------------------------------------------------------------------
866
# Function        : CopyDir
867
#
868
# Description     : Copy a directory to a target dir
869
#
870
# Inputs          : $src_dir    - Local to the user
871
#                                 Symbolic Name
872
#                   $dst_dir    - Within the output workspace
873
#                   Options
423 dpurdie 874
#                       --Merge             - Don't delete first
875
#                       --Source=Name       - Source via Symbolic Name
4147 dpurdie 876
#                       --FromPackage       - Source via package roots
4152 dpurdie 877
#                       --NoIgnoreDbgFiles  - Do not ignore .dbg and .debug files in dir copy
878
#                       --IfPresent         - Not an error if the path cannot be found
407 dpurdie 879
#
880
# Returns         :
881
#
882
sub CopyDir
883
{
884
    my ($src_dir, $dst_dir, @opts) = @_;
885
    my $opt_merge;
886
    my $opt_base;
411 dpurdie 887
    my $from_interface = 0;
4152 dpurdie 888
    my $ignoreDbg = 1;
889
    my $ignoreNoDir;
890
    my $user_src_dir = $src_dir;
891
    my $opt_source;
892
    my $opt_package;
407 dpurdie 893
 
894
    $dst_dir = $DebianWorkDir . '/' . $dst_dir;
895
    $dst_dir =~ s~//~/~;
896
 
897
    #
4152 dpurdie 898
    #   Scan and collect user options
407 dpurdie 899
    #
900
    foreach  ( @opts )
901
    {
4152 dpurdie 902
        Verbose2 ("CopyDir: $_");
407 dpurdie 903
        if ( m/^--Merge/ ) {
904
            $opt_merge = 1;
4152 dpurdie 905
 
407 dpurdie 906
        } elsif ( m/^--Source=(.+)/ ) {
425 dpurdie 907
            Error ("Source directory can only be specified once")
4152 dpurdie 908
                if ( defined $opt_source );
909
            $opt_source = $1;
425 dpurdie 910
 
4152 dpurdie 911
        } elsif ( m/^--FromPackage/ ) {
912
            Error ("FromPackage can only be specified once")
913
                if ( defined $opt_package );
914
            $opt_package = 1;
915
 
916
        } elsif ( m/^--NoIgnoreDbgFiles/ ) {
917
            $ignoreDbg = 0;
918
 
919
        } elsif ( m/^--IfPresent/ ) {
920
            $ignoreNoDir = 1;
407 dpurdie 921
 
4152 dpurdie 922
        } else {
923
            Error ("CopyDir: Unknown option: $_" );
924
        }
925
    }
411 dpurdie 926
 
4152 dpurdie 927
    #
928
    #   All options have been gathered. Now process some of them
929
    #
930
    Error ("CopyDir: Cannot use both --Source and --FromPackage: $src_dir") if ($opt_source && $opt_package);
425 dpurdie 931
 
4152 dpurdie 932
    #
933
    #   Convert a symbolic path into a physical path
934
    #
935
    if ($opt_source)
936
    {
937
        Verbose2 ("CopyDir: Determine Source: $opt_source");
425 dpurdie 938
 
4152 dpurdie 939
        $opt_source = lc($opt_source);
940
        my %CopyDirSymbolic = (
941
            'interfaceincdir'   => $opt_interfaceincdir,
942
            'interfacelibdir'   => $opt_interfacelibdir,
943
            'interfacebindir'   => $opt_interfacebindir,
944
            'libdir'            => $opt_libdir,
945
            'bindir'            => $opt_bindir,
946
            'localincdir'       => $opt_localincdir,
947
            'locallibdir'       => $opt_locallibdir,
948
            'localbindir'       => $opt_localbindir,
949
            'packagebindir'     => $opt_pkgbindir,
950
            'packagelibdir'     => $opt_pkglibdir,
951
            'packagepkgdir'     => $opt_pkgpkgdir,
952
            'packagedir'        => $opt_pkgdir,
953
        );
425 dpurdie 954
 
4152 dpurdie 955
        if ( exists $CopyDirSymbolic{$opt_source} )
956
        {
957
            $opt_base = $CopyDirSymbolic{$opt_source};
425 dpurdie 958
 
959
            #
4152 dpurdie 960
            #   If sourceing from interface, then follow
961
            #   symlinks in the copy. All files will be links anyway
425 dpurdie 962
            #
963
            $from_interface = 1
4152 dpurdie 964
                if ( $opt_source =~ m~^interface~ );
965
        }
966
        else
967
        {
968
            DebugDumpData ("CopyDirSymbolic", \%CopyDirSymbolic);
969
            Error ("CopyDir: Unknown Source Name: $opt_source" );
970
        }
971
    }
425 dpurdie 972
 
4152 dpurdie 973
    #
974
    #   Locate the path within an external package
975
    #
976
    if ($opt_package)
977
    {
978
        Verbose2 ("CopyDir: FromPackage: $src_dir");
4147 dpurdie 979
 
4152 dpurdie 980
        my @path;
981
        foreach my $entry ( getPackageList() )
982
        {
983
            my $base = $entry->getBase(3);
984
            next unless ( defined $base );
985
            if ( -d $base . '/' . $src_dir )
986
            {
987
                push @path, $base;
988
                $from_interface = 1
989
                    if ( $entry->{'TYPE'} eq 'interface' );
990
            }
407 dpurdie 991
        }
4152 dpurdie 992
 
993
        if ( $#path < 0 )
994
        {
995
            Error ("CopyDir: Cannot find source dir in any package: $user_src_dir") unless ($ignoreNoDir);
996
            Message ("CopyDir: Optional path not found: $user_src_dir");
997
            return;
998
        }
999
 
1000
        Error ("CopyDir: Requested path found in mutiple packages: $user_src_dir",
1001
                @path ) if ( $#path > 0 );
1002
        $opt_base = pop @path;
1003
 
1004
        #
1005
        #   If sourceing from interface, then follow symlinks in the copy.
1006
        #   All files will be links anyway
1007
        #
1008
        #   This is a very ugly test for 'interface'
1009
        #
1010
        $from_interface = 1
1011
            if ( $opt_base =~ m~/interface/~ );
1012
 
407 dpurdie 1013
    }
1014
 
4152 dpurdie 1015
    #
1016
    #   Create the full source path
1017
    #   May be: from a package, from a known directoru, from a local directory
1018
    #
1019
 
407 dpurdie 1020
    $src_dir = $opt_base . '/' . $src_dir if ( $opt_base );
1021
    $src_dir =~ s~//~/~g;
1022
    $src_dir =~ s~/$~~;
1023
 
1024
    Verbose ("CopyDir: $src_dir, $dst_dir");
4152 dpurdie 1025
    unless ( -d $src_dir )
1026
    {
1027
        Error ("CopyDir: Directory not found: $user_src_dir") unless ($ignoreNoDir);
1028
        Message ("CopyDir: Optional path not found: $user_src_dir");
1029
        return;
1030
    }
407 dpurdie 1031
 
1032
    #
423 dpurdie 1033
    #   Setup the copy options
407 dpurdie 1034
    #
423 dpurdie 1035
    my %copyOpts;
4101 dpurdie 1036
    $copyOpts{'IgnoreDirs'} = ['.svn', '.git', '.cvs', '.hg'];
1037
    $copyOpts{'Ignore'} = ['.gbedir', '_gbedir'];
4147 dpurdie 1038
    push (@{$copyOpts{'Ignore'}}, '*.debug', '*.dbg') if $ignoreDbg;
423 dpurdie 1039
    $copyOpts{'EmptyDirs'} = 1;
1040
    $copyOpts{'DeleteFirst'} = 1 unless $opt_merge;
1041
    $copyOpts{'Log'} = 1 if ( $opt_verbose > 1 );
1042
    $copyOpts{'DuplicateLinks'} = 1 unless ( $from_interface );
407 dpurdie 1043
 
1044
    #
423 dpurdie 1045
    #   Transfer the directory
407 dpurdie 1046
    #
423 dpurdie 1047
    JatsCopy::CopyDir ( $src_dir, $dst_dir, \%copyOpts );
407 dpurdie 1048
 
1049
    #
1050
    #   Expand link files that may have been copied in
1051
    #
1052
    Verbose ("Locate LINKFILES in $DebianWorkDir");
1053
    ExpandLinkFiles();
1054
}
1055
 
1056
#-------------------------------------------------------------------------------
1057
# Function        : AddInitScript
1058
#
1059
# Description     : Add an Init Script to the target
1060
#                   Optionally create start and stop links
1061
#
1062
# Inputs          : $script     - Name of the init script
1063
#                   $start      - Start Number
1064
#                   $stop       - Stop Number
1065
#                   Options:
1066
#                       --NoCopy        - Don't copy the script, just add links
1067
#                       --Afc           - Place in AFC init area
1068
#                       --FromPackage   - Source is in a package
1069
#
1070
# Returns         : 
1071
#
1072
sub AddInitScript
1073
{
1074
    my $no_copy;
1075
    my $basedir = "";
1076
    my @args;
1077
    my $from_package = 0;
1078
 
4302 dpurdie 1079
    # This directive is only available on the VIX platforms
1080
    #   Kludgey test - at the moment
407 dpurdie 1081
    #
4302 dpurdie 1082
    if ($opt_pkgarch =~ m~i386~)
1083
    {
1084
        Error ("AddInitScript is not supported on this platform"); 
1085
    }
1086
 
1087
    #
407 dpurdie 1088
    #   Process and Remove options
1089
    #
1090
    foreach  ( @_ )
1091
    {
1092
        if ( m/^--NoCopy/ ) {
1093
            $no_copy = 1;
1094
 
1095
        } elsif ( m/^--Afc/ ) {
1096
            $basedir = "/afc";
1097
 
1098
        } elsif ( m/^--FromPackage/ ) {
1099
            $from_package = 1;
1100
 
1101
        } elsif ( m/^--/ ) {
1102
            Error ("AddInitScript: Unknown option: $_");
1103
 
1104
        } else {
1105
            push @args, $_;
1106
 
1107
        }
1108
    }
1109
 
1110
    my( $script, $start, $stop ) = @args;
1111
    Error ("No script file specified") unless ( $script );
1112
    Warning("AddInitScript: No start or stop index specified") unless ( $start || $stop );
1113
    Verbose ("AddInitScript: $script, " . ($start || 'No Start') . ", " . ($stop || 'No Stop'));
1114
    $script = ResolveFile($from_package, $script );
1115
 
1116
    my $tdir = $basedir . "/etc/init.d/init.d";
1117
    my $base = StripDir($script);
1118
 
1119
    CopyFile( $script, $tdir ) unless $no_copy;
1120
 
1121
    my $link;
1122
    if ( $start )
1123
    {
1124
        $link = sprintf ("${basedir}/etc/init.d/S%2.2d%s", $start, $base );
1125
        MakeSymLink( "$tdir/$base", $link);
1126
    }
1127
 
1128
    if ( $stop )
1129
    {
1130
        $link = sprintf ("${basedir}/etc/init.d/K%2.2d%s", $stop, $base );
1131
        MakeSymLink( "$tdir/$base", $link);
1132
    }
1133
}
1134
 
1135
#-------------------------------------------------------------------------------
1136
# Function        : CatFile
1137
#
1138
# Description     : Copy a file to the end of a file
1139
#
1140
# Inputs          : $src
1141
#                   $dst    - Within the output workspace
1142
#
1143
# Returns         :
1144
#
1145
sub CatFile
1146
{
1147
    my ($src, $dst) = @_;
1148
 
1149
    $dst = $DebianWorkDir . '/' . $dst;
1150
    $dst =~ s~//~/~;
1151
    Verbose ("CatFile: $src, $dst");
1152
    $src = ResolveFile(0, $src );
1153
 
1154
    open (SF, '<', $src)  || Error ("CatFile: Cannot open $src");
1155
    open (DF, '>>', $dst) || Error ("CatFile: Cannot create:$dst");
1156
    while ( <SF> )
1157
    {
1158
        print DF $_;
1159
    }
1160
    close (SF);
1161
    close (DF);
1162
}
1163
 
1164
#-------------------------------------------------------------------------------
1165
# Function        : EchoFile
1166
#
1167
# Description     : Echo simple text to a file
1168
#
1169
# Inputs          : $file   - Within the output workspace
1170
#                   $text
1171
#
1172
# Returns         : 
1173
#
1174
sub EchoFile
1175
{
1176
    my ($file, $text) = @_;
1177
    Verbose ("EchoFile: $file");
1178
 
1179
    $file = $DebianWorkDir . '/' . $file;
1180
    $file =~ s~//~/~;
1181
 
1182
    unlink $file;
1183
    open (DT, ">", $file ) || Error ("Cannot create $file");
1184
    print DT  $text || Error ("Cannot print to $file");
1185
    close DT;
1186
}
1187
 
1188
#-------------------------------------------------------------------------------
4640 dpurdie 1189
# Function        : ConvertFiles
1190
#
1191
# Description     : This sub-routine is used to remove all carrage return\line
1192
#                   feeds from a line and replace them with the platform
1193
#                   specific equivalent chars.
1194
#
1195
#                   We let PERL determine what characters are written to the
1196
#                   file base on the  platform you are running on.
1197
#
1198
#                   i.e. LF    for unix
1199
#                        CR\LF for win32
1200
#
1201
# Inputs          : outPath                 - Output directory
1202
#                   flist                   - List of files in that directory
1203
#                   or
1204
#                   SearchOptions           - Search options to find files
1205
#                                           --Recurse
1206
#                                           --NoRecurse
1207
#                                           --FilterIn=xxx
1208
#                                           --FilterInRe=xxx
1209
#                                           --FilterOut=xxx
1210
#                                           --FilterOutRe=xxx
1211
#                   Common options
1212
#                                           --Dos
1213
#                                           --Unix
1214
#
1215
#
1216
# Returns         : 1
1217
#
1218
sub ConvertFiles
1219
{
1220
    my @uargs;
1221
    my $lineEnding = "\n";
1222
    my ($dosSet, $unixSet);
1223
    my $search =  JatsLocateFiles->new( '--NoRecurse' );
1224
 
1225
    #
1226
    #   Process user arguments extracting options
1227
    #
1228
    foreach  ( @_ )
1229
    {
1230
        if ( m~^--Recurse~ ) {
1231
            $search->recurse(1);
1232
 
1233
        } elsif ( m~^--NoRecurse~) {
1234
            $search->recurse(0);
1235
 
1236
        } elsif ( /^--FilterOut=(.*)/ ) {
1237
            $search->filter_out($1);
1238
 
1239
        } elsif ( /^--FilterOutRe=(.*)/ ) {
1240
            $search->filter_out_re($1);
1241
 
1242
        } elsif ( /^--FilterIn=(.*)/ ) {
1243
            $search->filter_in($1);
1244
 
1245
        } elsif ( /^--FilterInRe=(.*)/ ) {
1246
            $search->filter_in_re($1);
1247
 
1248
        } elsif ( m~^--Dos~) {
1249
            $lineEnding = "\r\n";
1250
            $dosSet = 1;
1251
 
1252
        } elsif ( m~^--Unix~) {
1253
            $lineEnding = "\n";
1254
            $unixSet = 1;
1255
 
1256
        } elsif ( m~^--~) {
4641 dpurdie 1257
            Error ("ConvertFiles: Unknown option: $_");
4640 dpurdie 1258
 
1259
        } else {
1260
            push @uargs, $_;
1261
        }
1262
    }
1263
 
1264
    #
1265
    #   Process non-option arguments
1266
    #       - Base dir
1267
    #       - List of files
1268
    #
1269
    my ($outPath, @flist) = @uargs;
1270
    Error ("ConvertFiles: Target Dir must be specified" ) unless ( $outPath );
1271
 
1272
    #
1273
    #   Sanity Tests
1274
    #
1275
    Error ("ConvertFiles: --Dos and --Unix are mutually exclusive" ) if ( $dosSet && $unixSet );
1276
 
1277
 
1278
    #
1279
    # Convert output path to physical path
1280
    #
1281
    my $topDir = catdir($DebianWorkDir, $outPath);
1282
    Verbose("ConvertFiles: topDir: $topDir");
1283
    Error ("ConvertFiles: Path does not exist", $topDir) unless ( -e $topDir );
1284
    Error ("ConvertFiles: Path is not a directory", $topDir) unless ( -d $topDir );
1285
 
1286
    #
1287
    #   Need to determine if we are searching or simply using a file list
1288
    #   There are two forms of the functions. If any of the search options have
1289
    #   been used then we assume that we are searchine
1290
    #
1291
    if ( $search->has_filter() )
1292
    {
1293
        Error ("ConvertFiles: Cannot mix search options with named files") if ( @flist );
1294
        @flist = $search->search($topDir);
1295
    }
1296
    Error ("ConvertFiles: No files specified") unless ( @flist );
1297
 
1298
    #
1299
    #   Process all named files
1300
    #
1301
    foreach my $file ( @flist )
1302
    {
1303
 
1304
        # this is our file that we want to clean.
1305
        my ($ifileLoc) = "$topDir/$file";
1306
        my ($tfileLoc) = "$topDir/$file\.tmp";
4641 dpurdie 1307
        Verbose("ConvertFiles: $file");
4640 dpurdie 1308
 
1309
        # we will check to see if the file exists.
1310
        #
1311
        my $ifile;
1312
        my $tfile;
1313
        if ( -f "$ifileLoc" )
1314
        {
1315
            open ($ifile, "< $ifileLoc" ) or
1316
                Error("Failed to open file [$ifileLoc] : $!");
1317
 
1318
            open ($tfile, "> $tfileLoc" ) or
1319
                Error("Failed to open file [$tfileLoc] : $!");
1320
            binmode $tfile;
1321
 
1322
            while ( <$ifile> ) 
1323
            {
1324
                s~[\n\r]+$~~;               # Chomp
1325
                print $tfile "$_" . $lineEnding;
1326
            }
1327
        }
1328
        else
1329
        {
1330
            Error("ConvertFiles [$ifileLoc] does not exist.");
1331
        }
1332
 
1333
        close $ifile;
1334
        close $tfile;
1335
 
1336
 
1337
        # lets replace our original file with the new one
1338
        #
1339
        if(File::Copy::move("$tfileLoc", "$ifileLoc"))
1340
        {
1341
            Verbose2("ConvertFiles: Renamed [$tfileLoc] to [$ifileLoc] ...");
1342
        }
1343
        else
1344
        {
1345
            Error("ConvertFiles: Failed to rename file [$tfileLoc] to [$ifileLoc]: $!");
1346
        }
1347
    }
1348
 
1349
    return 1;
1350
}
1351
 
4641 dpurdie 1352
#----------------------------------------------------------------------------
1353
# Function        : ReplaceTags
1354
#
1355
# Description     : This sub-routine is used to replace Tags in one or more files
1356
#
1357
# Inputs          : outPath                 - Output directory
1358
#                   flist                   - List of files in that directory
1359
#                   or
1360
#                   SearchOptions           - Search options to find files
1361
#                                           --Recurse
1362
#                                           --NoRecurse
1363
#                                           --FilterIn=xxx
1364
#                                           --FilterInRe=xxx
1365
#                                           --FilterOut=xxx
1366
#                                           --FilterOutRe=xxx
1367
#                   Common options
1368
#                                           --Tag=Tag,Replace
1369
#                                           
1370
#
1371
# Returns         : 1
1372
#
1373
sub ReplaceTags
1374
{
1375
    my @uargs;
1376
    my $search =  JatsLocateFiles->new( '--NoRecurse' );
1377
    my @tagsList;
1378
    my $tagSep = ',';
1379
    my @tagOrder;
1380
    my %tagData;
1381
 
1382
    #
1383
    #   Process user arguments extracting options
1384
    #
1385
    foreach  ( @_ )
1386
    {
1387
        if ( m~^--Recurse~ ) {
1388
            $search->recurse(1);
1389
 
1390
        } elsif ( m~^--NoRecurse~) {
1391
            $search->recurse(0);
1392
 
1393
        } elsif ( /^--FilterOut=(.*)/ ) {
1394
            $search->filter_out($1);
1395
 
1396
        } elsif ( /^--FilterOutRe=(.*)/ ) {
1397
            $search->filter_out_re($1);
1398
 
1399
        } elsif ( /^--FilterIn=(.*)/ ) {
1400
            $search->filter_in($1);
1401
 
1402
        } elsif ( /^--FilterInRe=(.*)/ ) {
1403
            $search->filter_in_re($1);
1404
 
1405
        } elsif ( m~^--Tag=(.*)~) {
1406
            push @tagsList, $1;
1407
 
1408
        } elsif ( m~^--~) {
1409
            Error ("ReplaceTags: Unknown option: $_");
1410
 
1411
        } else {
1412
            push @uargs, $_;
1413
        }
1414
    }
1415
 
1416
    #
1417
    #   Process non-option arguments
1418
    #       - Base dir
1419
    #       - List of files
1420
    #
1421
    my ($outPath, @flist) = @uargs;
1422
    Error ("ReplaceTags: Target Dir must be specified" ) unless ( $outPath );
1423
 
1424
    #
1425
    #   Sanity Tests
1426
    #
1427
    Error ("ReplaceTags: No tags specified" ) unless ( @tagsList );
1428
 
1429
    #
1430
    # Convert output path to physical path
1431
    #
1432
    my $topDir = catdir($DebianWorkDir, $outPath);
1433
    Verbose("ReplaceTags: topDir: $topDir");
1434
    Error ("ReplaceTags: Path does not exist", $topDir) unless ( -e $topDir );
1435
    Error ("ReplaceTags: Path is not a directory", $topDir) unless ( -d $topDir );
1436
 
1437
    #
1438
    #   Convert Tags into pairs for latter use
1439
    #
1440
    my $sep = quotemeta ($tagSep );
1441
    foreach my $tag ( @tagsList )
1442
    {
1443
        my ($tname,$tvalue) = split ( $sep, $tag );
1444
        Error ("No tag value in: $tag" ) unless ( defined $tvalue );
1445
        Error ("Duplicate Tag: $tname" ) if ( exists $tagData{$tname} );
1446
        Verbose ("Tag: $tname :: $tvalue");
1447
        push @tagOrder, $tname;
1448
        $tagData{$tname} = $tvalue;
1449
    }
1450
 
1451
    #
1452
    #   Need to determine if we are searching or simply using a file list
1453
    #   There are two forms of the functions. If any of the search options have
1454
    #   been used then we assume that we are searchine
1455
    #
1456
    if ( $search->has_filter() )
1457
    {
1458
        Error ("ReplaceTags: Cannot mix search options with named files") if ( @flist );
1459
        @flist = $search->search($topDir);
1460
    }
1461
    Error ("ReplaceTags: No files specified") unless ( @flist );
1462
 
1463
    #
1464
    #   Process all named files
1465
    #
1466
    foreach my $file ( @flist )
1467
    {
1468
 
1469
        # this is our file that we want to clean.
1470
        my ($ifileLoc) = "$topDir/$file";
1471
        my ($tfileLoc) = "$topDir/$file\.tmp";
1472
        Verbose("ReplaceTags: $file");
1473
 
1474
        # we will check to see if the file exists.
1475
        #
1476
        my $ifile;
1477
        my $tfile;
1478
        if ( -f "$ifileLoc" )
1479
        {
1480
            open ($ifile, "< $ifileLoc" ) or
1481
                Error("Failed to open file [$ifileLoc] : $!");
1482
 
1483
            open ($tfile, "> $tfileLoc" ) or
1484
                Error("Failed to open file [$tfileLoc] : $!");
1485
 
1486
            while ( <$ifile> ) 
1487
            {
1488
                s~[\n\r]+$~~;               # Chomp
1489
 
1490
                #
1491
                #   Perform tag replacement
1492
                #
1493
                foreach my $tag ( @tagOrder )
1494
                {
1495
                    my $value = $tagData{$tag};
1496
                    if ( s~$tag~$value~g )
1497
                    {
1498
                        Verbose2("Replaced: $tag with $value");
1499
                    }
1500
                }
1501
 
1502
                print $tfile "$_\n";
1503
            }
1504
        }
1505
        else
1506
        {
1507
            Error("ReplaceTags [$ifileLoc] does not exist.");
1508
        }
1509
 
1510
        close $ifile;
1511
        close $tfile;
1512
 
1513
 
1514
        # lets replace our original file with the new one
1515
        #
1516
        if(File::Copy::move("$tfileLoc", "$ifileLoc"))
1517
        {
1518
            Verbose2("ReplaceTags: Renamed [$tfileLoc] to [$ifileLoc] ...");
1519
        }
1520
        else
1521
        {
1522
            Error("ReplaceTags: Failed to rename file [$tfileLoc] to [$ifileLoc]: $!");
1523
        }
1524
    }
1525
 
1526
    return 1;
1527
}
1528
 
4640 dpurdie 1529
#-------------------------------------------------------------------------------
407 dpurdie 1530
# Function        : SetFilePerms
1531
#
1532
# Description     : Set file permissions on one or more files or directories
1533
#
1534
# Inputs          : $perm           - Perm Mask
1535
#                   @paths          - List of paths/files to process
1536
#                   Options
1537
#                       --Recurse   - Recurse subdirs
1538
#
1539
# Returns         : 
1540
#
1541
sub SetFilePerms
1542
{
1543
 
1544
    my @args;
1545
    my $perms;
1546
    my $recurse = 0;
1547
 
1548
    #
1549
    #   Process and Remove options
1550
    #
1551
    foreach  ( @_ )
1552
    {
1553
        if ( m/^--Recurse/ ) {
1554
            $recurse = 1;
1555
 
1556
        } elsif ( m/^--/ ) {
1557
            Error ("SetFilePerms: Unknown option: $_");
1558
 
1559
        } else {
1560
            push @args, $_;
1561
 
1562
        }
1563
    }
1564
 
1565
    $perms = shift @args;
1566
    Error ("SetFilePerms: No Permissions" ) unless ( $perms );
1567
 
1568
    foreach my $path ( @args )
1569
    {
1570
        Verbose ("Set permissions; $perms, $path");
1571
        my $full_path = $DebianWorkDir . '/' . $path;
1572
        if ( -f $full_path )
1573
        {
1574
            System ('chmod', $perms, $full_path );
1575
        }
1576
        elsif ( -d $full_path )
1577
        {
1578
            System ('chmod', '-R', $perms, $full_path ) if ($recurse);
1579
            System ('chmod', $perms, $full_path ) unless ($recurse);
1580
        }
1581
        else
1582
        {
1583
            Warning("SetFilePerms: Path not found: $path");
1584
        }
1585
    }
1586
}
1587
 
1588
#-------------------------------------------------------------------------------
4636 dpurdie 1589
# Function        : SetPermissions 
1590
#
1591
# Description     : Called to set permissions of files/dirs in a directory structure.
1592
#                   With no options sets DirTag and all files/dirs in it to perms
1593
#   
1594
# Inputs          : path        - The directory tag to start setting permissions on
1595
#                   Options     - See below
1596
#       
1597
#   Required Options:
1598
#       One or both of
1599
#               --FilePerms=    Sets the permissions of files to this permission.
1600
#                               If not supplied then no files have their permissions changed
1601
#               --DirPerms=     Sets the permissions of directories to this permission
1602
#                               If not supplied then no directories have their permissions changed
1603
#       OR
1604
#               --Perms=        Sets the permissions of both files and directories to this permissions
1605
#                               Equivalent to supplying both --FilePerms=X && --DirPerms=X
1606
#               
1607
#   Options:                    
1608
#               --RootOnly      Only sets the permissions on the 'path' directory/file, 
1609
#                               all other options ignored
1610
#               --SkipRoot      Does not set permissions on the 'path' directory/file, 
1611
#                               obviously mutually exlusive with --RootOnly
1612
#   
1613
#       Any option supported by JatsLocateFiles. 
1614
#       Some of these include:
1615
#               
1616
#               --Recurse       Recurse the directory tree.  Does a depth first recurse so that all 
1617
#                               dir entries are processed before the dir itself (default)
1618
#               --NoRecurse     Dont recurse
1619
#               --FilterIn=     Apply permissions to files/directories that matches this value.
1620
#               --FilterInRe=   Perl RE's can be used (Not Shell wildcards) and this option
1621
#                               can be supplied mulitple times
1622
#               --FilterOut=    Dont apply permissions to any files/directories matching this value
1623
#               --FilterOutRe=  Perl RE's can be used (Not Shell wildcards) and this option
1624
#                               can be supplied mulitple times
1625
#               
1626
#                               FilterIn is applied before FilterOut.  If Recurse is specified 
1627
#                               the directory will be recursed regardless of these filters, however
1628
#                               the filter will be applied when it comes time to chmod the dir 
1629
#
1630
#------------------------------------------------------------------------------
1631
sub SetPermissions
1632
{
1633
    my ( $path, $filePerms, $dirPerms, $someDone );
1634
    my ( $rootOnly, $skipRoot ) = ( 0, 0 );
1635
 
1636
    my $search =  JatsLocateFiles->new( '--Recurse', '--DirsToo' );
1637
 
1638
    foreach ( @_ )
1639
    {
1640
        if ( m/^--Perms=(.*)/ ) {
1641
            $filePerms = $1;
1642
            $dirPerms = $1;
1643
 
1644
        } elsif (m/^--FilePerms=(.*)/ )  {
1645
            $filePerms = $1;
1646
 
1647
        } elsif ( m/^--DirPerms=(.*)/ )  {
1648
            $dirPerms = $1;
1649
 
1650
        }  elsif ( m/^--RootOnly/ ) {
1651
            $rootOnly = 1;
1652
 
1653
        } elsif ( m/^--SkipRoot/ )  {
1654
            $skipRoot = 1;
1655
 
1656
        } elsif ( m/^--Filter/ && $search->option( $_ ) ) {
1657
            Verbose2 ("Search Option: $_" );
1658
 
1659
        } elsif ( m/^--Recurse|--NoRecurse/ && $search->option( $_ ) ) {
1660
            Verbose2 ("Search Option: $_" );
1661
 
1662
        } elsif (m/^--/ ) {
1663
            Error ("SetPermissions: Unknown option: $_");
1664
 
1665
        } else  {
1666
            Error("SetPermissions 'path' already set", "Path: $_") if ( $path );
1667
            $path = $_;
1668
        }
1669
    }
1670
 
1671
    #
1672
    #   Sanity test
1673
    #
1674
    Error("SetPermissions called with out a 'path' parameter") if ( !defined($path) );
1675
    Error("SetPermissions called with out any Permissions specified") if ( !defined($filePerms) && !defined($dirPerms) );
1676
    Error("SetPermissions: Options --RootOnly & --SkipRoot are mutually exclusive" ) if ( $rootOnly && $skipRoot );
1677
 
1678
 
1679
    #   Convert the target directory name into a physical path
1680
    #   User specifies '/' as the root of the image
1681
    #   User specifies 'name' as relateve to the root of the image
1682
    #
1683
    my $topDir = $DebianWorkDir . '/' . $path;
1684
    $topDir =~ s~/+$~~;
1685
 
1686
    Verbose("SetPermissions: Called with options " . join(", ", @_));
1687
 
1688
    #
1689
    #   Only set perms on the root directory
1690
    #       This is a trivial operation
1691
    #
1692
    if ( $rootOnly )
1693
    {
1694
        $someDone += chmodItem( $topDir, $filePerms, $dirPerms );
1695
    }
1696
    else
1697
    {
1698
        #
1699
        #   Create a list of files/dirs to process
1700
        #
1701
        my @elements = $search->search( $topDir );
1702
 
1703
        foreach my $dirEntry ( @elements )
1704
        {
1705
            my $fullPath = "$topDir/$dirEntry";
1706
 
1707
            # A dir and we dont have dirperms, so skip
1708
            if ( -d $fullPath && !defined($dirPerms) )
1709
            {
1710
                Verbose2("SetPermissions: Skipping dir $fullPath as we have no dir permissions");
1711
                next;
1712
            }
1713
 
1714
            # A file and we dont have fileperms, so skip
1715
            if ( -f $fullPath && !defined($filePerms) )
1716
            {
1717
                Verbose2("SetPermissions: Skipping file $fullPath as we have no file permissions");
1718
                next;
1719
            }
1720
 
1721
            # a file or a dir and have the right permissions and we are not recursing
1722
            if ( -f $fullPath || -d $fullPath )
1723
            {
1724
                $someDone += chmodItem( $fullPath, $filePerms, $dirPerms );
1725
            }
1726
            else
1727
            {
1728
                Warning("SetPermissions: Skipping $fullPath as its not a file or directory");
1729
            }
1730
        }
1731
 
1732
        #
1733
        #   Process the topDir
1734
        #   May not be modified if --SkipRoot has been requested
1735
        #
1736
        if ( !$skipRoot && -e $topDir )
1737
        {
1738
            $someDone += chmodItem( $topDir, $filePerms, $dirPerms );
1739
        }
1740
    }
1741
 
1742
    #   Final warning
1743
    #
1744
    Warning ("SetPermissions: No files located", "Args: @_") unless ( $someDone );
1745
}
1746
 
1747
#-------------------------------------------------------------------------------
1748
# Function        : chmodItem 
1749
#
1750
# Description     : Internal
1751
#                   chmod a file or a folder
1752
#
1753
# Inputs          : item                        - Item to mod
1754
#                   filePerms                   - File perms
1755
#                   dirPerms                    - dire perms
1756
#
1757
# Returns         : 1   - Item modified
1758
#                   0   - Item not modified
1759
#
1760
sub chmodItem
1761
{
1762
    my ($item, $filePerms, $dirPerms) = @_;
1763
 
1764
    if ( -d $item && defined $dirPerms)
1765
    {
1766
        Verbose("SetPermissions: $dirPerms : $item");
1767
        System ('chmod', $dirPerms, $item );
1768
        return 1;
1769
    }
1770
 
1771
    if ( -f $item  && defined $filePerms)
1772
    {
1773
        Verbose("SetPermissions: $filePerms : $item");
1774
        System ('chmod', $filePerms, $item );
1775
        return 1;
1776
    }
1777
 
1778
    return 0;
1779
}
1780
 
1781
 
1782
#-------------------------------------------------------------------------------
407 dpurdie 1783
# Function        : CreateDir
1784
#
1785
# Description     : Create a directory within the target workspace
1786
#
1787
# Inputs          : $path           - Name of the target directory
1788
#
1789
# Returns         : Nothing
1790
#
1791
sub CreateDir
1792
{
1793
    my ($path) = @_;
1794
 
1795
    Verbose ("Create Dir: $path");
1796
    mkpath( $DebianWorkDir . '/' . $path );
1797
}
1798
 
1799
#-------------------------------------------------------------------------------
1800
# Function        : IsProduct
1801
#                   IsPlatform
1802
#                   IsTarget
427 dpurdie 1803
#                   IsVariant
407 dpurdie 1804
#
1805
# Description     : This function allows some level of control in the
1806
#                   packaging scripts. It will return true if the current
1807
#                   product is listed.
1808
#
1809
#                   Ugly after thought
1810
#
1811
#                   Intended use:
1812
#                       Xxxxxx(...) if (IsProduct( 'aaa',bbb' );
1813
#
1814
# Inputs          : products    - a list of products to compare against
1815
#
1816
# Returns         : True if the current build is for one of the listed products
1817
#
1818
sub IsProduct
1819
{
1820
    foreach ( @_ )
1821
    {
1822
        return 1 if ( $opt_product eq $_ );
1823
    }
1824
    return 0;
1825
}
1826
 
1827
sub IsPlatform
1828
{
1829
    foreach ( @_ )
1830
    {
1831
        return 1 if ( $opt_platform eq $_ );
1832
    }
1833
    return 0;
1834
}
1835
 
1836
sub IsTarget
1837
{
1838
    foreach ( @_ )
1839
    {
1840
        return 1 if ( $opt_target eq $_ );
1841
    }
1842
    return 0;
1843
}
1844
 
427 dpurdie 1845
sub IsVariant
1846
{
1847
    foreach ( @_ )
1848
    {
1849
        return 1 if ( $opt_variant eq $_ );
1850
    }
1851
    return 0;
1852
}
407 dpurdie 1853
 
1854
#-------------------------------------------------------------------------------
1855
# Function        : FindFiles
1856
#
1857
# Description     : Locate files within a given dir tree
1858
#
1859
# Inputs          : $root           - Base of the search
1860
#                   $match          - Re to match
1861
#
1862
# Returns         : A list of files that match
1863
#
1864
my @FIND_LIST;
1865
my $FIND_NAME;
1866
 
1867
sub FindFiles
1868
{
1869
    my ($root, $match ) = @_;
1870
    Verbose2("FindFiles: Root: $root, Match: $match");
1871
 
1872
    #
1873
    #   Becareful of closure, Must use globals
1874
    #
1875
    @FIND_LIST = ();
1876
    $FIND_NAME = $match;
1877
    File::Find::find( \&find_files, $root);
1878
 
1879
    #
1880
    #   Find callback program
1881
    #
1882
    sub find_files
1883
    {
1884
        my $item =  $File::Find::name;
1885
 
1886
        return if ( -d $File::Find::name );
1887
        return unless ( $_ =~ m~$FIND_NAME~ );
1888
        push @FIND_LIST, $item;
1889
    }
1890
    return @FIND_LIST;
1891
}
1892
 
1893
#-------------------------------------------------------------------------------
1894
# Function        : CalcRelPath
1895
#
1896
# Description     : Return the relative path to the current working directory
1897
#                   as provided in $Cwd
1898
#
1899
# Inputs          : $Cwd - Base dir
1900
#                   $base - Path to convert
1901
#
1902
# Returns         : Relative path from the $Cwd
1903
#
1904
sub CalcRelPath
1905
{
1906
    my ($Cwd, $base) = @_;
1907
 
1908
    my @base = split ('/', $base );
1909
    my @here = split ('/', $Cwd );
1910
    my $result;
1911
 
1912
    Debug("RelPath: Source: $base");
1913
 
1914
    return $base unless ( $base =~ m~^/~ );
1915
 
1916
    #
1917
    #   Remove common bits from the head of both lists
1918
    #
1919
    while ( $#base >= 0 && $#here >= 0 && $base[0] eq $here[0] )
1920
    {
1921
        shift @base;
1922
        shift @here;
1923
    }
1924
 
1925
    #
1926
    #   Need to go up some directories from here and then down into base
1927
    #
1928
    $result = '../' x ($#here + 1);
1929
    $result .= join ( '/', @base);
1930
    $result = '.' unless ( $result );
1931
    $result =~ s~//~/~g;
1932
    $result =~ s~/$~~;
1933
 
1934
    Debug("RelPath: Result: $result");
1935
    return $result;
1936
}
1937
 
1938
#-------------------------------------------------------------------------------
1939
# Function        : ExpandLinkFiles
1940
#
1941
# Description     : Look for .LINK files in the output image and expand
1942
#                   the links into softlinks
1943
#
1944
# Inputs          : None
1945
#                   The rouine works on the $DebianWorkDir directory tree
1946
#
1947
# Returns         : Nothing
1948
#                   Will remove .LINKS files that are processed
1949
#
1950
sub ExpandLinkFiles
1951
{
1952
    foreach my $linkfile ( FindFiles( $DebianWorkDir, ".LINKS" ))
1953
    {
1954
        next if ( $linkfile =~ m~/\.svn/~ );
1955
        my $BASEDIR = StripFileExt( $linkfile );
1956
        $BASEDIR =~ s~^$DebianWorkDir/~~;
1957
        Verbose "Expand links: $BASEDIR";
1958
 
1959
        open (LF, "<", $linkfile ) || Error ("Cannot open link file: $linkfile" );
1960
        while ( <LF> )
1961
        {
1962
            chomp;
1963
            next if ( m~^#~ );
1964
            next unless ( $_ );
1965
            my ($link, $file) = split;
1966
 
1967
            MakeSymLink($file ,"$BASEDIR/$link", '--NoDotDot' );
1968
        }
1969
        close (LF);
1970
        unlink $linkfile;
1971
    }
1972
}
1973
 
1974
#-------------------------------------------------------------------------------
1975
# Function        : ResolveFile
1976
#
1977
# Description     : Determine where the source for a file is
415 dpurdie 1978
#                   Will look in (default):
407 dpurdie 1979
#                       Local directory
1980
#                       Local Include
415 dpurdie 1981
#                   Or  (FromPackage)
1982
#                       Our Package directory
1983
#                       Interface directory (BuildPkgArchives)
1984
#                       Packages (LinkPkgArchive)
1985
#
407 dpurdie 1986
#                   Will scan 'parts' subdirs
1987
#
1988
# Inputs          : $from_package       - 0 - Local File
1989
#                   $file
1990
#
1991
# Returns         : Path
1992
#
1993
sub ResolveFile
1994
{
1995
    my ($from_package, $file) = @_;
1996
    my $wildcard = ($file =~ /[*?]/);
415 dpurdie 1997
    my @path;
407 dpurdie 1998
 
1999
    #
415 dpurdie 2000
    #   Determine the paths to search
2001
    #
2002
    if ( $from_package )
2003
    {
2004
        unless ( @ResolveFileList )
2005
        {
2006
            push @ResolveFileList, $opt_pkgdir;
2007
            foreach my $entry ( getPackageList() )
2008
            {
2009
                push @ResolveFileList, $entry->getBase(3);
2010
            }
2011
        }
2012
        @path = @ResolveFileList;
2013
    }
2014
    else
2015
    {
2016
        @path = ('.', $opt_localincdir);
2017
    }
2018
 
2019
    #
407 dpurdie 2020
    #   Determine a full list of 'parts' to search
2021
    #   This is provided within the build information
2022
    #
2023
    my @parts = getPlatformParts ();
2024
    push @parts, '';
2025
 
2026
    my @done;
2027
    foreach my $root (  @path )
2028
    {
2029
        foreach my $subdir ( @parts )
2030
        {
2031
            my $sfile;
415 dpurdie 2032
            $sfile = "$root/$subdir/$file";
2033
            $sfile =~ s~//~/~g;
2034
            $sfile =~ s~^./~~g;
2035
            Verbose2("LocateFile: $sfile, $root, $subdir");
2036
            if ( $wildcard )
2037
            {
2038
                push @done, glob ( $sfile );
2039
            }
2040
            else
2041
            {
2042
                push @done, $sfile if ( -f $sfile || -l $sfile )
2043
            }
407 dpurdie 2044
        }
2045
    }
2046
 
415 dpurdie 2047
    Error ("ResolveFile: File not found: $file", "Search Path:", @path)
407 dpurdie 2048
        unless ( @done );
2049
 
2050
    Warning ("ResolveFile: Multiple instances of file found. Only first is used", @done)
2051
        if ( $#done > 0 && ! $wildcard && !wantarray );
2052
 
2053
    return wantarray ? @done : $done[0];
2054
}
2055
 
2056
#-------------------------------------------------------------------------------
2057
# Function        : ResolveBinFile
2058
#
415 dpurdie 2059
# Description     : Determine where the source for a BIN file is
2060
#                   Will look in (default):
2061
#                       Local directory
2062
#                       Local Include
2063
#                   Or  (FromPackage)
2064
#                       Our Package directory
2065
#                       Interface directory (BuildPkgArchives)
2066
#                       Packages (LinkPkgArchive)
407 dpurdie 2067
#                   Will scan 'parts' subdirs
2068
#
2069
# Inputs          : $from_package       - 0 - Local File
415 dpurdie 2070
#                   $file
407 dpurdie 2071
#
2072
# Returns         : Path
2073
#
2074
sub ResolveBinFile
2075
{
2076
    my ($from_package, $file) = @_;
2077
    my @path;
2078
    my @types;
2079
    my $wildcard = ($file =~ /[*?]/);
2080
 
415 dpurdie 2081
    #
2082
    #   Determine the paths to search
2083
    #
407 dpurdie 2084
    if ( $from_package )
2085
    {
415 dpurdie 2086
        unless ( @ResolveBinFileList )
2087
        {
2088
            push @ResolveBinFileList, $opt_pkgdir . '/bin';
2089
            foreach my $entry ( getPackageList() )
2090
            {
2091
                if ( my $path = $entry->getBase(3) )
2092
                {
2093
                    $path .= '/bin';
2094
                    push @ResolveBinFileList, $path if ( -d $path );
2095
                }
2096
            }
2097
        }
2098
        @path = @ResolveBinFileList;
407 dpurdie 2099
        @types = ($opt_type, '');
2100
    }
2101
    else
2102
    {
2103
        @path = ($opt_bindir, $opt_localbindir);
2104
        @types = '';
2105
    }
2106
 
2107
    #
2108
    #   Determine a full list of 'parts' to search
2109
    #   This is provided within the build information
2110
    #
2111
    my @parts = getPlatformParts ();
2112
    push @parts, '';
2113
 
2114
    my @done;
2115
    foreach my $root (  @path )
2116
    {
2117
        foreach my $subdir ( @parts )
2118
        {
2119
            foreach my $type ( @types )
2120
            {
2121
                my $sfile;
2122
                $sfile = "$root/$subdir$type/$file";
2123
                $sfile =~ s~//~/~g;
2124
                Verbose2("LocateBinFile: $sfile");
2125
                if ( $wildcard )
2126
                {
429 dpurdie 2127
                    foreach  ( glob ( $sfile ) )
2128
                    {
4143 dpurdie 2129
                        # Ignore .dbg (vix) and .debug (qt) files.
429 dpurdie 2130
                        next if ( m~\.dbg$~ );
4143 dpurdie 2131
                        next if ( m~\.debug$~ );
429 dpurdie 2132
                        push @done, $_;
2133
                    }
407 dpurdie 2134
                }
2135
                else
2136
                {
415 dpurdie 2137
                    push @done, $sfile if ( -f $sfile || -l $sfile )
407 dpurdie 2138
                }
2139
            }
2140
        }
2141
    }
2142
 
415 dpurdie 2143
    Error ("ResolveBinFile: File not found: $file", "Search Path:", @path)
407 dpurdie 2144
        unless ( @done );
2145
 
2146
    Warning ("ResolveBinFile: Multiple instances of file found. Only first is used", @done)
2147
        if ( $#done > 0 && ! $wildcard && !wantarray );
2148
    return wantarray ? @done : $done[0];
2149
}
2150
 
2151
#-------------------------------------------------------------------------------
2152
# Function        : ResolveLibFile
2153
#
415 dpurdie 2154
# Description     : Determine where the source for a LIB file is
2155
#                   Will look in (default):
2156
#                       Local directory
2157
#                       Local Include
2158
#                   Or  (FromPackage)
2159
#                       Our Package directory
2160
#                       Interface directory (BuildPkgArchives)
2161
#                       Packages (LinkPkgArchive)
407 dpurdie 2162
#                   Will scan 'parts' subdirs
2163
#
4672 dpurdie 2164
# Inputs          : $from_package   - 0:Local File
2165
#                   $file           - Basename for a 'realname'
2166
#                                     Do not provide 'lib' or '.so' or version info
2167
#                                     May contain embedded options
2168
#                                       --Dll           - Use Windows style versioned DLL
2169
#                                       --VersionDll    - Use the versioned DLL
2170
#                                       --3rdParty      - Use exact name provided
407 dpurdie 2171
#
2172
# Returns         : Path
2173
#
2174
sub ResolveLibFile
2175
{
2176
    my ($from_package, $file) = @_;
2177
    my $wildcard = ($file =~ /[*?]/);
2178
    my @options;
2179
    my $num_dll;
415 dpurdie 2180
    my @path;
407 dpurdie 2181
    #
2182
    #   Extract options from file
2183
    #
409 alewis 2184
    $num_dll = 0;
407 dpurdie 2185
    ($file, @options) = split ( ',', $file);
2186
    foreach ( @options )
2187
    {
2188
        if ( m/^--Dll/ ) {
2189
            $num_dll = 1;
2190
        } elsif ( m/^--VersionDll/ ) {
2191
            $num_dll = 2;
4672 dpurdie 2192
        } elsif ( m/^--3rdParty/ ) {
2193
            $num_dll = 3;
407 dpurdie 2194
        } else {
2195
            Error ("Unknown suboption to ResolveLibFile: $_" );
2196
        }
2197
    }
2198
 
2199
    #
415 dpurdie 2200
    #   Determine the paths to search
2201
    #
2202
    if ( $from_package )
2203
    {
2204
        unless ( @ResolveLibFileList )
2205
        {
2206
            push @ResolveLibFileList, $opt_pkgdir . '/lib';
2207
            foreach my $entry ( getPackageList() )
2208
            {
2209
                push @ResolveLibFileList, $entry->getLibDirs(3);
2210
            }
2211
        }
2212
        @path = @ResolveLibFileList;
2213
    }
2214
    else
2215
    {
2216
        @path = ($opt_libdir, $opt_locallibdir);
2217
    }
2218
 
2219
    #
407 dpurdie 2220
    #   Determine a full list of 'parts' to search
2221
    #   This is provided within the build information
2222
    #
2223
    my @parts = getPlatformParts ();
2224
    push @parts, '';
2225
 
2226
    my @done;
2227
    foreach my $root (  @path )
2228
    {
2229
        foreach my $type ( $opt_type, '' )
2230
        {
2231
            foreach my $subdir ( @parts )
2232
            {
2233
                my $sfile;
2234
                my $exact;
2235
                if ( $num_dll == 2 ) {
2236
                    $sfile = $file . $type . '.*.dll' ;
2237
                } elsif ( $num_dll == 1 ) {
2238
                    $sfile = $file . $type . '.dll' ;
2239
                    $exact = 1;
4672 dpurdie 2240
                } elsif ( $num_dll == 3 ) {
2241
                    $sfile = $file;
2242
                    $exact = 1;
407 dpurdie 2243
                } else {
2244
                    $sfile = "lib" . $file . $type . '.so.*';
2245
                }
2246
 
2247
                $sfile = "$root/$subdir/$sfile";
2248
                $sfile =~ s~//~/~g;
2249
                Verbose2("LocateLibFile: $sfile");
2250
                if ( $exact )
2251
                {
415 dpurdie 2252
                    push @done, $sfile if ( -f $sfile || -l $sfile );
407 dpurdie 2253
                }
419 dpurdie 2254
                elsif ($num_dll)
407 dpurdie 2255
                {
2256
                    push @done, glob ( $sfile );
2257
                }
419 dpurdie 2258
                else
2259
                {
2260
                    #
2261
                    #   Looking for .so files
2262
                    #   Filter out the soname so files
2263
                    #   Assume that the soname is shorter than the realname
4143 dpurdie 2264
                    #       Ignore .dbg (vix) and .debug (qt) files.
419 dpurdie 2265
                    #
2266
                    my %sieve;
2267
                    foreach ( glob ( $sfile )  )
2268
                    {
429 dpurdie 2269
                        next if ( m~\.dbg$~ );
4143 dpurdie 2270
                        next if ( m~\.debug$~ );
421 alewis 2271
                        m~(.*\.so\.)([\d\.]*\d)$~;
2272
                        if ( $1 )
2273
                        {
2274
                            my $file = $1;
2275
                            my $len = exists $sieve{$file} ? length($sieve{$file}) : 0;
2276
                            $sieve{$file} = $_
2277
                                if ( $len == 0 || length($_) > $len );
2278
                        }                                
419 dpurdie 2279
                    }
2280
 
2281
                    push @done, values %sieve;
2282
                }
407 dpurdie 2283
            }
2284
        }
2285
    }
2286
 
415 dpurdie 2287
    Error ("ResolveLibFile: File not found: $file", "Search Path:", @path)
407 dpurdie 2288
        unless ( @done );
2289
 
2290
    Warning ("ResolveLibFile: Multiple instances of file found. Only first is used", @done)
2291
        if ( $#done > 0 && ! $wildcard && !wantarray );
2292
 
2293
    return wantarray ? @done : $done[0];
2294
}
2295
 
2296
 
2297
#-------------------------------------------------------------------------------
2298
# Function        : AUTOLOAD
2299
#
2300
# Description     : Intercept bad user directives and issue a nice error message
2301
#                   This is a simple routine to report unknown user directives
2302
#                   It does not attempt to distinguish between user errors and
2303
#                   programming errors. It assumes that the program has been
2304
#                   tested. The function simply report filename and line number
2305
#                   of the bad directive.
2306
#
2307
# Inputs          : Original function arguments ( not used )
2308
#
2309
# Returns         : This function does not return
2310
#
2311
our $AUTOLOAD;
2312
sub AUTOLOAD
2313
{
2314
    my $fname = $AUTOLOAD;
2315
    $fname =~ s~^main::~~;
2316
    my ($package, $filename, $line) = caller;
2317
 
2318
    Error ("Directive not known or not allowed in this context: $fname",
2319
           "Directive: $fname( @_ );",
2320
           "File: $filename, Line: $line" );
2321
}
2322
 
2323
 
2324
1;
2325