#!/usr/bin/env perl

#---------------------------------------------------------------------
#                          file information
#---------------------------------------------------------------------

# File:     setup-branding-albusluna
# Purpose:  Sets up branding for browser
# License:  BSD-style (for this file only)
# Revision: 211215

#---------------------------------------------------------------------
#                            module setup
#---------------------------------------------------------------------

require 5.10.1;
use strict;
use Carp;
use warnings;
use Cwd;
use File::Find;
                                # Trap warnings
$SIG {__WARN__} = sub { die @_; };

#---------------------------------------------------------------------
#                           basic constants
#---------------------------------------------------------------------

use constant ZERO  => 0;        # Zero
use constant ONE   => 1;        # One
use constant TWO   => 2;        # Two

use constant FALSE => 0;        # Boolean FALSE
use constant TRUE  => 1;        # Boolean TRUE

#---------------------------------------------------------------------
#                         program parameters
#---------------------------------------------------------------------

my $MAX_FILE_SIZE = 15 * 1024 * 1024;

#---------------------------------------------------------------------
#                          global variables
#---------------------------------------------------------------------

my $CWD;                        # Current working directory
my @Paths = ();                 # List of pathname entries

#---------------------------------------------------------------------
#                    directory traversal routines
#---------------------------------------------------------------------

# "AdjustList"  is a  "find"-compatible  list preprocessor.  This pre-
# processor is used by a "find" command in the main routine.

#---------------------------------------------------------------------

sub AdjustList
{
    my (@list) = @_;
    grep { !-l && !m@^\.{1,2}\z@; } @list;
}

#---------------------------------------------------------------------

# "ProcEntry"  is a  "find"-compatible file processor.  This processor
# is used by a "find" command in the main routine.

# Note: This routine must preserve "$_".

#---------------------------------------------------------------------

sub ProcEntry
{
    my $path;                   # Absolute pathname
                                # Filename (provided by "File::Find")
    my $name = "$File::Find::name";

    $name =~ s@^(\./)+@@;       # Strip leading occurrences of "./"
    $path =  "$CWD/$name";      # Absolute pathname
    $path =~ s@^//+@/@;         # Kludge

    push (@Paths, $path);       # Save path
    undef;
}

#---------------------------------------------------------------------
#                            main routine
#---------------------------------------------------------------------

sub Main
{
    my $BaseDir;                # Base directory
    my $OutPath;                # Pathname to display
    my $LEN_CWD;                # Length of CWD path
    my $unsafe;                 # Flag: Unsafe to run here

    my $data;                   # Data buffer
    my $path;                   # Absolute path
    my $pattern;                # Pattern string
    my $str;                    # Scratch

    my $Pattern;                # Regular-expression pattern string
    my $NewText;                # Replacement text

#---------------------------------------------------------------------
# Initial setup.

    select (STDERR); $| = ONE;
    select (STDOUT); $| = ONE;
                                # Fix problems for some filesystems
    $File::Find::dont_use_nlink = ONE;
    undef $/;

#---------------------------------------------------------------------

    my $CONAME_OTHER       = 'Moonchild Productions'   ;
    my $CONAME_THIS        = 'Laclin'                  ;

    my $LCNAME_OTHER       = 'palemoon'                ;
    my $LCNAME_THIS        = 'albusluna'               ;

    my $UCNAME_OTHER       = uc ($LCNAME_OTHER )       ;
    my $UCNAME_THIS        = uc ($LCNAME_THIS  )       ;

    my $CCNAME_SPC_OTHER   = 'Pale Moon'               ;
    my $CCNAME_SPC_THIS    = 'Albus Luna'              ;

    my $VENDOR_SHORT_OTHER = '"Moonchild"'             ;
    my $VENDOR_SHORT_THIS  = '"Laclin"'                ;

    my $LCNAME_SPC_OTHER   = lc ($CCNAME_SPC_OTHER )   ;
    my $LCNAME_SPC_THIS    = lc ($CCNAME_SPC_THIS  )   ;

#---------------------------------------------------------------------

    $str =  $VENDOR_SHORT_OTHER;
    $str =~ s@"@@g;
    my      $VENDOR_UNQUO_OTHER = $str;

    $str =  $VENDOR_SHORT_THIS;
    $str =~ s@"@@g;
    my      $VENDOR_UNQUO_THIS  = $str;

#---------------------------------------------------------------------

    $str =  $CCNAME_SPC_OTHER;
    $str =~ s@\s+@@g;
    my $CCNAME_NSP_OTHER = $str;

    $str =  $CCNAME_SPC_THIS;
    $str =~ s@\s+@@g;
    my $CCNAME_NSP_THIS  = $str;

#---------------------------------------------------------------------

    my $TRADEMARKS_OTHER =  << 'END';
trademark(s|) of Moonchild Productions \(M.C. Straver BASc\)
END
       $TRADEMARKS_OTHER =~ s@\s+\z@@s;

    my $TRADEMARKS_THIS  =  << 'END';
unregistered trademark$1 of Laclin
END
       $TRADEMARKS_THIS  =~ s@\s+\z@@s;

#---------------------------------------------------------------------

    if ((!-d "$LCNAME_OTHER") || (!-d 'other-licenses'))
    {
        print << 'END';
Error: setup-branding-$LCNAME_THIS should be run in the top-level
directory of the $LCNAME_THIS source tree.
END
        exit ONE;
    }

    if ((-e "$LCNAME_THIS") || (-l "$LCNAME_THIS"))
    {
        print << 'END';
Error: An object named $LCNAME_THIS already exists in the top-level
directory of the $LCNAME_THIS source tree.
END
        exit ONE;
    }

#---------------------------------------------------------------------

    open (OFD, ">LICENSE") || die;
    print OFD << 'END';
See  the  following file for the  copyright  and  licensing conditions
attached to this codebase,  including copies of the  licenses concern-
ed:
../rest/mozilla/toolkit/content/license.html

You are not granted rights or licenses to the intellectual property or
trademarks of the Mozilla Foundation or any other party.
END
    close (OFD) || die;

#---------------------------------------------------------------------

    open (OFD, ">README.md") || die;
    print OFD << "END";
# $LCNAME_THIS web browser

This is the source code for the $LCNAME_THIS web browser, an independent
browser derived from Firefox/Mozilla community code. The source tree
is laid out in a "comm-central" style configuration where only the
code specific to $LCNAME_THIS is kept in this subtree.

The shared Unified XUL Platform source code is referenced here as a
git submodule contained in the `platform/` directory and is required
to build the application.

You should have received the both the source code in question and
"build" instructions in the same source tarball or other archive
as this file.
END
    close (OFD) || die;

#---------------------------------------------------------------------

    $CWD = getcwd();            # Get absolute path for directory

                                # To be documented
    my $prgicon  = "$CWD/albusluna.png";
    die "IE 0282 $CWD $prgicon\n"  unless -f $prgicon;

    system "sed -e '/Mark Straver/d' -i AUTHORS";
    rename ($LCNAME_OTHER, $LCNAME_THIS) || die;
    chdir                 ($LCNAME_THIS) || die;

#---------------------------------------------------------------------

    $str = << "END";
sed
-e "s/^MOZ_APP_BASENAME=.*/MOZ_APP_BASENAME=$CCNAME_NSP_THIS/" \
-i confvars.sh
END
    $str =~ s@\s+@ @g;
    $str =~ s@\s+\z@@s;
    system $str;

#---------------------------------------------------------------------

    open (OFD, ">LICENSE") || die;
    print OFD << 'END';
See  the  following file for the  copyright  and  licensing conditions
attached to this codebase,  including copies of the  licenses concern-
ed:
../../rest/mozilla/toolkit/content/license.html

You are not granted rights or licenses to the intellectual property or
trademarks of the Mozilla Foundation or any other party.
END
    close (OFD) || die;

#---------------------------------------------------------------------

    open (OFD, ">branding/LICENSE") || die;
    print OFD << 'END';
These branding files, including files in  subdirectories, but with the
exception of the files in the ./unofficial subdirectory, are (c) Copy-
right Laclin Productions. All rights reserved.

No part of these  graphical or textual files may be used in any third-
party product  without express prior written  permission by the  copy-
right holder.

Even though  these files are included in a  source tree released under
the  Mozilla Public License 2.0,  and may be included  in publicly re-
leased executable code versions of free software products, you are not
granted any trademark rights or licenses  to the intellectual property
of  any party's intellectual property,  including trademarked names or
logos.
END
    close (OFD) || die;

#---------------------------------------------------------------------
# Directory setup.

    $BaseDir = '.';             # Base is '.' (current directory)
    $CWD     = getcwd();        # Get absolute path for directory
    $LEN_CWD = length ($CWD);   # Save length of absolute path

#---------------------------------------------------------------------
# Build a pathname list.

    my %args =
    (
        bydepth    => TRUE         ,
        preprocess => \&AdjustList ,
        wanted     => \&ProcEntry
    );

    find (\%args, '.');
    @Paths = sort @Paths;

#---------------------------------------------------------------------
# Process directory tree.

    for $path (@Paths)
    {
        $str     =  $path;
        $str     =~ s@^(.{$LEN_CWD})@@;
        $str     =~ s@^/+@@;
        $OutPath =  $str;

# Note:  ".pdf" files  *must* be skipped,  because the "-T" test isn't
# reliable for PDFs. For most other file types, filename-based exclus-
# ion isn't strictly necessary,  but it speeds things up,  because the
# time required for "-l", "-f", and "-T" tests may be  significant for
# large directory trees.

        next if $path =~
m@\.(bz2|gif|gz|jpe?g|mp[234]|pdf|png|tar|tgz|xls|wav|wmv|zip)\z@i;

        next if -l $path;

        my @stat = stat $path;
        next if !-f _;
        next if !-T _ && $path !~ m@\.nsi\z@;
        next if $stat [7] > $MAX_FILE_SIZE;

        open (IFD, "<$path") || die "Error #03: $OutPath\n";
        binmode (IFD);
        $data = <IFD>;
        $data = "" unless defined ($data);
        close (IFD);

        next if $data =~ m@sub\s+ProcEntry@;
        my $orig_data = $data;

#---------------------------------------------------------------------
# Make the required changes.

        $data =~ s@$TRADEMARKS_OTHER@$TRADEMARKS_THIS@g     ;

        $data =~ s@$CONAME_OTHER@$CONAME_THIS@g             ;
        $data =~ s@$LCNAME_OTHER@$LCNAME_THIS@g             ;
        $data =~ s@$UCNAME_OTHER@$UCNAME_THIS@g             ;

        $data =~ s@$CCNAME_NSP_OTHER@$CCNAME_NSP_THIS@g     ;
        $data =~ s@$CCNAME_SPC_OTHER@$CCNAME_SPC_THIS@g     ;
        $data =~ s@$LCNAME_SPC_OTHER@$LCNAME_SPC_THIS@g     ;

        $data =~ s@$VENDOR_SHORT_OTHER@$VENDOR_SHORT_THIS@g ;
        $data =~ s@$VENDOR_UNQUO_OTHER@$VENDOR_UNQUO_THIS@g ;

        $str  =  $CCNAME_NSP_THIS;
        $data =~ s@'$str', '\w+'@'$str'@;

        $data =~ s@\n.*See.+Productions/.+/issues/.+\s*\n@\n@;
        $data =~ s@, see bug #\d+@@g;

#---------------------------------------------------------------------
# Save changes to current file (if necessary).

        if ($data ne $orig_data)
        {
            my ($mtime) = (stat $path) [9];
            die "Error #04: $path\n" if !defined ($mtime);

            open (OFD, ">$path") || die "Error #05: $path\n";
            print OFD $data;
            close (OFD) || die "Error #06: $path\n";
            utime ($mtime, $mtime, $path);

            print "$path\n";
        }

#---------------------------------------------------------------------
# Rename current file (if necessary).

        my $newpath =  $path;
           $newpath =~ s@$LCNAME_OTHER@$LCNAME_THIS@g;

        if ($path ne $newpath)
        {
            rename ($path, $newpath) || die;
        }
    }

#---------------------------------------------------------------------
# Replace official branding images.

    die unless -d 'branding';

    my $pnglist =  `find branding/ -type f -name \*.png`;
       $pnglist =~ s@\s+\z@@s;
       $pnglist =~ s@^\s+@@s;
    my @pnglist = split (/\s+/, $pnglist);
       @pnglist = grep { !m@(unofficial|back|word)@i; } @pnglist;

                                # Sanity check
    die unless scalar (@pnglist) > 6;

    for my $pngfile (sort @pnglist)
    {
        my $info = `file $pngfile 2>&1`;
        die unless $info =~ m@(\d+) x \d@;
        my $width =  $1;
        my $cmd   =  << "END";
convert -scale ${width}x $prgicon $pngfile;
END
           $cmd   =~ s@\s+\z@@s;
        print "$cmd\n";
        system $cmd;           
    }

#---------------------------------------------------------------------
# Wrap it up.

    print "Done\n";		# Print a status message
    undef;
}

#---------------------------------------------------------------------
#                            main program
#---------------------------------------------------------------------

&Main();                        # Call the main routine
exit ZERO;                      # Normal exit
