#!/usr/bin/perl -w
use strict;

# Author: Martin Pitt <martin.pitt@ubuntu.com>
# Copyright: (C) 2011 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

=head1 NAME

dh_ubuntu_defaults - build defaults customization package

=cut

use strict;

use Debian::Debhelper::Dh_Lib;
use Errno;
use File::Path;
use File::Copy;

=head1 SYNOPSIS

B<dh_ubuntu_defaults> [S<B<debhelper options>>]

=head1 DESCRIPTION

ubuntu-defaults-builder allows you to easily create a "default settings"
package for Ubuntu. The B<ubuntu-defaults-template> script will generate a
source package with the customizable settings (e. g.  desktop/background.jpg
and firefox/bookmarks-menu.txt). When built and installed, it will take the
necessary actions to modify the system-wide defaults for desktops, programs,
etc.

The main purpose for this is to provide a standard and
safe way to create localized Ubuntu images, or OEM custom projects.

B<dh_ubuntu_defaults> is a debhelper program which implements the main logic of
these defaults packages by converting the simple configuration files from the
defaults source package into the configuration file format used by the target
applications and desktop environments, and adding the corresponding maintainer
script code like file diversions.

It is usually not necessary to know about or deal with this program manually.
The intended mode of operation is to call B<ubuntu-defaults-template> to create
a skeleton source package (which will call B<dh_ubuntu_defaults>), and then
customize the example configuration files.

=cut

# return an array of lines from given file, with comments sorted out
sub lines {
    my ($fname) = @_;
    my @lines = ();

    if (not open F, $fname) {
	return @lines if ($!{ENOENT}); # missing files are OK
	die "cannot open $fname: $!";
    }
    while (<F>) {
	s/#.*$//;
	s/^\s*//;
	s/\s*$//;
	push @lines, $_ if $_;
    }
    close F;

    return @lines;
}

# process depends.txt and recommends.txt
sub dependencies {
    my $package = shift;

    my @depends = lines('depends.txt');
    my @recommends = lines('recommends.txt');

    addsubstvar($package, 'ubuntudefaults:Depends', join(', ', @depends));
    addsubstvar($package, 'ubuntudefaults:Recommends', join(', ', @recommends));
}

# process desktop/background.jpg
sub desktop_background {
    my $package = shift;
    my $tmp = tmpdir($package);

    return unless -s 'desktop/background.jpg';

    mkpath("$tmp/usr/share/backgrounds");
    copy('desktop/background.jpg', "$tmp/usr/share/backgrounds/$package.jpg");

    mkpath("$tmp/usr/share/glib-2.0/schemas/");
    open F, '>>', "$tmp/usr/share/glib-2.0/schemas/$package.gschema.override" or die "Cannot create gschema override: $!";
    print F "[org.gnome.desktop.background]
picture-uri='file:///usr/share/backgrounds/$package.jpg'
";
    close F;

    # set the same in gconf as well, for older GNOME and gsettings-data-convert
    mkpath("$tmp/usr/share/gconf/defaults/");
    open F, '>>', "$tmp/usr/share/gconf/defaults/zz_$package" or die "Cannot create gconf override: $!";
    print F "/desktop/gnome/background/picture_filename \"/usr/share/backgrounds/$package.jpg\"\n";
    close F;
}

# unity/launchers.txt
sub unity_launchers {
    my $package = shift;
    my $tmp = tmpdir($package);

    my @lines = lines('unity/launchers.txt');
    return unless @lines;

    # get current default launcher list for Unity
    open F, '/usr/share/glib-2.0/schemas/com.canonical.Unity.gschema.xml' or die "cannot open Unity gschema: $!";
    read F, $_, 10000;
    close F;
    my ($v) = /<key.*?name="favorites".*?>\s*<default>\s*\[(.*?)\]\s*<\/default>/s;
    $v =~ s/'//g;
    $v =~ s/\s+//g;
    my @defaults = split /,/, $v;

    # append custom defaults
    push @defaults, map ($_ .= '.desktop', @lines);

    # Unity uses gsettings, write schema
    $v = join(', ', map("'$_'", @defaults));
    mkpath("$tmp/usr/share/glib-2.0/schemas/");
    open F, '>>', "$tmp/usr/share/glib-2.0/schemas/$package.gschema.override" or die "Cannot create gschema override: $!";
    print F "[com.canonical.Unity.Launcher]
favorites=[$v]
";
    close F;

    # Unity 2D still uses gconf
    $v = join(',', @defaults);
    mkpath("$tmp/usr/share/gconf/ubuntu-2d/default/");
    open F, '>>', "$tmp/usr/share/gconf/ubuntu-2d/default/zz_$package" or die "Cannot create gconf override: $!";
    print F "/desktop/unity-2d/launcher/favorites [$v]\n";
    close F;
    autoscript $package, 'postinst', 'postinst-ubuntu2d-launchers';
}

# multimedia/radiostations.txt
sub radio_stations {
    my $package = shift;
    my $tmp = tmpdir($package);

    my @lines = lines('multimedia/radiostations.txt');
    return unless @lines;

    # for Rhythmbox
    mkpath("$tmp/usr/lib/rhythmbox/plugins/iradio");
    open F, '>', "$tmp/usr/lib/rhythmbox/plugins/iradio/iradio-initial.xspf" 
	or die "Cannot create iradio-initial.xspf: $!";
    print F '<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
  <trackList>
';
    foreach (@lines) {
	my @fields = split ';';
	map $_ =~ s/^\s+//, @fields;
	map $_ =~ s/\s+$//, @fields;
	map $_ =~ s/\&/\&amp;/, @fields;
	map $_ =~ s/</&lt;/, @fields;
	map $_ =~ s/>/&gt;/, @fields;
	if ($#fields != 2) {
	    warning "Invalid line in multimedia/radiostations.txt, expected 3 fields separated by ';': $_";
	    next;
	}
	print F "    <track>
      <title>$fields[2]</title>
      <location>$fields[0]</location>
      <extension application=\"http://www.rhythmbox.org\">
        <genre>$fields[1]</genre>
      </extension>
    </track>
";
    }
    print F '  </trackList>
</playlist>
';
    close F;
    autoscript $package, 'preinst', 'preinst-ubuntu-defaults-divert',
	"s/PACKAGE/$package/g; s_FILE_/usr/lib/rhythmbox/plugins/iradio/iradio-initial.xspf_g";
    autoscript $package, 'postrm', 'postrm-ubuntu-defaults-divert',
	"s/PACKAGE/$package/g; s_FILE_/usr/lib/rhythmbox/plugins/iradio/iradio-initial.xspf_g";
}

sub write_bookmarks {
    my $file = $_[0];
    my @lines = @{$_[1]};
    my $count = 1;

    foreach (@lines) {
	my ($url, $name) = split /\s+/, $_, 2;
	print $file "item.$count.title=\"$name\"
item.$count.link=$url
";
	++$count;
    }
}

# firefox/*
sub firefox {
    my $package = shift;
    my $tmp = tmpdir($package);

    my $startpage;
    my @lines = lines('firefox/startpage.txt');
    if (@lines) {
	if ($#lines > 0) {
	    warning 'Extra lines in firefox/startpage.txt, ignoring';
	}
	$startpage = $lines[0];
    }

    my $searchengine;
    @lines = lines('firefox/searchengine.txt');
    if (@lines) {
	if ($#lines > 0) {
	    warning 'Extra lines in firefox/searchengine.txt, ignoring';
	}
	$searchengine = $lines[0];
    }

    my @bookmarks_toolbar = lines('firefox/bookmarks-toolbar.txt');
    my @bookmarks_menu = lines('firefox/bookmarks-menu.txt');

    return if (!$startpage && !$searchengine && !@bookmarks_toolbar && !@bookmarks_menu);

    # TODO: change firefox-5.0 to firefox once firefox package is fixed to not
    # have versioned paths
    mkpath("$tmp/usr/lib/firefox-5.0/distribution/");
    open my $ini, '>', "$tmp/usr/lib/firefox-5.0/distribution/distribution.ini";
    print $ini '[Global]
id=canonical
version=1.0
about=Mozilla Firefox for Ubuntu

[Preferences]
app.distributor = "canonical"
app.distributor.channel = "ubuntu"
app.partner.ubuntu = "ubuntu"
';

    # startpage
    if ($startpage) {
	print $ini "browser.startup.homepage=\"$startpage\"
browser.startup.homepage_reset=\"$startpage\"
extensions.ubufox\@ubuntu.com.custom_homepage=\"$startpage\"
";
    }

    # default search engine
    if ($searchengine) {
	print $ini "browser.search.defaultenginename=\"$searchengine\"\n";
    }

    # bookmarks
    print $ini "\n[BookmarksToolbar]\n";
    write_bookmarks($ini, \@bookmarks_toolbar);
    print $ini "\n[BookmarksMenu]\n";
    write_bookmarks($ini, \@bookmarks_menu);

    close $ini;

    autoscript $package, 'preinst', 'preinst-ubuntu-defaults-divert',
	"s/PACKAGE/$package/g; s_FILE_/usr/lib/firefox-5.0/distribution/distribution.ini_g";
    autoscript $package, 'postrm', 'postrm-ubuntu-defaults-divert',
	"s/PACKAGE/$package/g; s_FILE_/usr/lib/firefox-5.0/distribution/distribution.ini_g";
}

init();

foreach my $package (@{$dh{DOPACKAGES}}) {
    dependencies($package);
    desktop_background($package);
    unity_launchers($package);
    radio_stations($package);
    firefox($package);
}

=head1 SEE ALSO

L<ubuntu-defaults-template(1)>, L<debhelper(1)>

=head1 AUTHOR

Martin Pitt <martin.pitt@ubuntu.com>

Copyright (C) 2011 Canonical Ltd., licensed under the GNU GPL v3 or later.

=cut
