#!/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;
use File::Find;
use File::Spec;
use JSON;

=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 webbrowser/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

# initialize global %macros hash
my %macros = ();
my @extra_depends = ();

my $template_dir = $ENV{'UBUNTU_DEFAULTS_TEMPLATE_DIR'} ||
    '/usr/share/ubuntu-defaults-builder/template/';

sub init_macros {
    $macros{'distro_release_number'} = `lsb_release -sr` or die "cannot run lsb_release: $!";
    chomp $macros{'distro_release_number'};
    $macros{'distro_release_name'} = `lsb_release -sc` or die "cannot run lsb_release: $!";
    chomp $macros{'distro_release_name'};
}

# return an array of lines from given file, with comments sorted out and macros
# replaced
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*$//;

	next unless $_;

	# substitute macros
	while (/\${(\w+)}/) {
	    my $var = $1;
	    error "unknown macro: $var" unless exists $macros{$var};
	    s/\${$var}/$macros{$var}/g;
	}

	push @lines, $_;
    }
    close F;

    return @lines;
}

# abort if customization is not allowed for this package; e. g. mere ubuntu
# localizations (package name starts with "ubuntu-") must not change the
# desktop behaviour too much
sub check_allowed {
    my $package = shift;
    my $file = shift;

    return if $dh{DISABLE_RESTRICTIONS};
    return unless $package =~ /^ubuntu-/;

    # check if our template (NOT the package's file) has a "NotUbuntu:" tag;
    # special-case background here as this is not a text file
    if ($file ne 'desktop/background.jpg' && -e "$template_dir/$file") {
	open F, "$template_dir/$file" or 
	die "cannot open template file $template_dir/$file: $!";
	read F, $_, 1000;
	close F;
	if ((index $_, 'NotUbuntu:') < 0) {
	    return; # can be changed
	}
    }

    # if we do not have a template for that file, assume that it cannot be
    # changed
    error "error: $file must not be changed for Ubuntu localizations (packages starting with \"ubuntu-\")";
}

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

    my @depends = lines('depends.txt');
    my @recommends = lines('recommends.txt');
    check_allowed($package, 'depends.txt') if @depends;
    check_allowed($package, 'recommends.txt') if @recommends;

    push @extra_depends, @depends;

    addsubstvar($package, 'ubuntudefaults:Depends', join(', ', @extra_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';
    check_allowed($package, '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;
}

# process desktop/*.desktop
sub desktop_files {
    my $package = shift;
    my $tmp = tmpdir($package);

    my @files = <desktop/*.desktop>;
    return unless @files;
    mkpath("$tmp/usr/share/applications");

    foreach (@files) {
	check_allowed($package, $_);
	File::Copy::copy $_, "$tmp/usr/share/applications/";
    }
}

# process desktop/default-applications.txt
sub desktop_default_applications {
    my $package = shift;
    my $tmp = tmpdir($package);

    my @lines = lines('desktop/default-applications.txt');
    return unless @lines;

    check_allowed($package, 'desktop/default-applications.txt');
    my @defaults = ();
    my @modified_mimetypes = ();

    # get new defaults
    for (@lines) {
	my @fields = split;
	if ($#fields != 1) {
	    warning "Invalid line in desktop/default-applications.txt, expected 2 fields separated by whitespace: $_";
	    next;
	}
	push @defaults, "$fields[0]=$fields[1].desktop";
	push @modified_mimetypes, $fields[0];
    }

    # read and print defaults while ignoring overridden default apps
    open F, '/usr/share/applications/defaults.list' or die "cannot open default application list file: $!";
    mkpath("$tmp/usr/share/applications");
    open my $newf, '>', "$tmp/usr/share/applications/defaults.list";
    SEARCH: while (<F>) {
	my($line) = $_;
	my($found);
	foreach my $mimetype (@modified_mimetypes) {
	    next SEARCH if ($line =~ m/\Q$mimetype\E/);
	}
    print $newf $line;
    }
    close F;
    # append custom defaults
    print $newf join "\n", @defaults;
    close $newf;

    autoscript $package, 'preinst', 'preinst-ubuntu-defaults-divert',
    "s/PACKAGE/$package/g; s_FILE_/usr/share/applications/defaults.list_g";
    autoscript $package, 'postrm', 'postrm-ubuntu-defaults-divert',
    "s/PACKAGE/$package/g; s_FILE_/usr/share/applications/defaults.list_g";
}

# process desktop/default-session.txt
sub desktop_default_session {
    my $package = shift;
    my $tmp = tmpdir($package);

    my @lines = lines('desktop/default-session.txt');
    return unless @lines;

    check_allowed($package, 'desktop/default-session.txt');

    if ($#lines > 0) {
	warning 'Extra lines in webbrowser/startpage.txt, ignoring';
    }

    mkpath("$tmp/usr/share/$package/");
    open my $f, '>', "$tmp/usr/share/$package/default-session.txt";
    print $f $lines[0];
    close $f;

    autoscript $package, 'postinst', 'postinst-ubuntu-defaults-desktop-session',
       "s/PACKAGE/$package/g;";
}

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

    my @lines = lines('unity/launchers.txt');
    return unless @lines;
    check_allowed($package, 'unity/launchers.txt');

    # get current default launcher list for Unity
    my @defaults = ();
    unless (grep { $_ eq '@clear' } @lines) {
	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;
	@defaults = split /,/, $v;
    } else {
	@lines = grep { $_ ne '@clear' } @lines;
    }

    # append custom defaults
    for (@lines) {
	my @fields = split;
	if ($#fields > 1) {
	    warning "Invalid line in unity/launchers.txt, expected at most 2 fields separated by whitespace: $_";
	    next;
	}
	push @defaults, "application://$fields[0].desktop";
	if ($fields[1]) {
	    push @extra_depends, $fields[1];
	}
    }

    # Unity uses gsettings, write schema
    my $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;
    check_allowed($package, 'multimedia/radiostations.txt');

    # for Rhythmbox
    mkpath("$tmp/usr/share/rhythmbox/plugins/iradio");
    open F, '>', "$tmp/usr/share/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/share/rhythmbox/plugins/iradio/iradio-initial.xspf_g";
    autoscript $package, 'postrm', 'postrm-ubuntu-defaults-divert',
	"s/PACKAGE/$package/g; s_FILE_/usr/share/rhythmbox/plugins/iradio/iradio-initial.xspf_g";

    # for Banshee
    mkpath "$tmp/usr/share/banshee/stations";
    symlink "/usr/share/rhythmbox/plugins/iradio/iradio-initial.xspf", 
	"$tmp/usr/share/banshee/stations/$package.xspf";
}

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;
    }
}

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

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

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

    my @bookmarks_toolbar = lines('webbrowser/bookmarks-toolbar.txt');
    my @bookmarks_menu = lines('webbrowser/bookmarks-menu.txt');
    check_allowed($package, 'webbrowser/bookmarks-toolbar.txt') if @bookmarks_toolbar;
    check_allowed($package, 'webbrowser/bookmarks-menu.txt') if @bookmarks_menu;

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

    mkpath("$tmp/usr/lib/firefox/distribution/");
    open my $ini, '>', "$tmp/usr/lib/firefox/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/distribution/distribution.ini_g";
    autoscript $package, 'postrm', 'postrm-ubuntu-defaults-divert',
	"s/PACKAGE/$package/g; s_FILE_/usr/lib/firefox/distribution/distribution.ini_g";
}

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

    my @lines = lines('i18n/language.txt');
    if ($#lines > 0) {
	warning 'Extra lines in i18n/language.txt, ignoring';
    }
    if (@lines) {
	check_allowed($package, 'i18n/language.txt');
	mkpath("$tmp/usr/share/$package/");
	open my $f, '>', "$tmp/usr/share/$package/language.txt";
	print $f $lines[0], "\n";
	close $f;
    }

    @lines = lines('i18n/langpacks.txt');
    if (@lines) {
	check_allowed($package, 'i18n/langpacks.txt');
	mkpath("$tmp/usr/share/$package/");
	open my $f, '>', "$tmp/usr/share/$package/langpacks.txt";
	print $f join "\n", @lines;
	close $f;
    }
}

sub check_valid_keyboard {
    my $layout = shift;
    my $variant = undef;
    $variant = $_[0] if @_;

    open my $f, '/usr/share/X11/xkb/rules/xorg.lst' or 
	die "cannot open /usr/share/X11/xkb/rules/xorg.lst: $!";
    # skip until the layout section
    while (<$f>) {
	last if /^! layout/;
    }

    # check validity of layout
    my $valid_layout = 0;
    while (<$f>) {
	if (/^!/) {
	    unless (/^! variant/) {
		error 'internal error: expected variant section after layout section';
	    }
	    last;
	}
	if (/^\s*$layout\s/) {
	    $valid_layout = 1;
	}
    }
    error "Invalid layout '$layout' in i18n/keyboard.txt; check /usr/share/X11/xkb/rules/xorg.lst for valid ones" unless $valid_layout;

    # check validity of variant
    return unless $variant;
    my $valid_variant = 0;
    while (<$f>) {
	last if /^!/;
	if (/^\s*$variant\s+$layout:/) {
	    $valid_variant = 1;
	    last;
	}
    }
    error "Invalid variant '$variant' in i18n/keyboard.txt; check /usr/share/X11/xkb/rules/xorg.lst for valid ones" unless $valid_variant;

    close $f;
}

# i18n/keyboard.txt
sub keyboard {
    my $package = shift;
    my $tmp = tmpdir($package);

    my @lines = lines('i18n/keyboard.txt');
    if ($#lines > 0) {
	warning 'Extra lines in i18n/keyboard.txt, ignoring';
    }
    return unless @lines;
    check_allowed($package, 'i18n/keyboard.txt');

    my @fields = split /\s+/, $lines[0];
    if ($#fields < 0 || $#fields > 1) {
	error 'Invalid format of i18n/keyboard.txt: Expecting 1 or 2 fields';
    }

    check_valid_keyboard @fields;

    mkpath("$tmp/usr/share/$package/");
    open my $f, '>', "$tmp/usr/share/$package/keyboard.txt";
    if ($#fields == 0) {
	print $f $lines[0];
    } else {
	print $f "$fields[0]_$fields[1]";
    }
    close $f;
}

# icons/
sub icons {
    my $package = shift;
    my $cwd = File::Spec->rel2abs('.');
    my $tmp = File::Spec->rel2abs(tmpdir($package));

    my $iter = sub {
	return if -l $_ or -d $_; # Skip directories and symlinks
	return unless /\.(jpg|jpeg|png|svg)$/;
	my $name = $_;

	# See if we were asked to exclude this file.
	foreach my $f (@{$dh{EXCLUDE}}) {
	    return if ($File::Find::name =~ m/\Q$f\E/);
	}

	doit "install -D -m 644 '$_' '$tmp/usr/share/icons/hicolor/$File::Find::name'";
    };

    chdir 'icons' || return;
    File::Find::find $iter, '.';
    chdir $cwd;
}

# ubiquity-slideshow/
sub ubiquity_slideshow {
    my $package = shift;
    my $tmp = File::Spec->rel2abs(tmpdir($package));
    my $tmp_extra_slides_dir = "$tmp/usr/share/ubiquity-slideshow/slides/extra";

    my $add_locale = sub {
	my $locale_name = shift;

	my @slides = ();
	my @media = ();

	my $add_locale_file = sub {
	    my $file = $_;

	    return unless -f $file;
	    return if $file =~ m/^\./;

	    doit "install -D -m 644 '$file' '$tmp_extra_slides_dir/$locale_name/$File::Find::name'";

	    if ($File::Find::dir eq '.') {
		# This file is a slide
		push(\@slides, $file);
	    } else {
		# This file is something else (we assume it's a media file)
		my $file_path = $File::Find::name;
		# Slideshow expects relative path without preceding './'
		$file_path = substr($file_path, 2);
		push(\@media, $file_path);
	    }
	};

	File::Find::find($add_locale_file, '.');

	my %locale_data = ();
	$locale_data{slides} = \@slides;
	$locale_data{media} = \@media;
	return %locale_data;
    };

    my $cwd = File::Spec->rel2abs('.');
    chdir "ubiquity-slideshow" || return;

    my %directory_data;

    opendir(my $locales_dh, "slides") || return;
    my @locales = grep { !/^\./ } readdir($locales_dh);
    closedir $locales_dh;

    foreach my $locale (@locales) {
	my $locale_dir = "slides/$locale";

	next unless -d $locale_dir;
	next if $locale =~ m/^\./;

	my $cwd = File::Spec->rel2abs('.');
	chdir $locale_dir || next;
	my %locale_data = &$add_locale($locale);
	chdir $cwd;

	if (%locale_data) {
	    $directory_data{$locale} = \%locale_data;
	}
    }

    if (%directory_data) {
	my $directory_json = to_json(\%directory_data);
	mkpath($tmp_extra_slides_dir);
	open F, '>', "$tmp_extra_slides_dir/directory.jsonp";
	print F "ubiquitySlideshowDirectoryCb($directory_json);";
	close F;
    }

    chdir $cwd;
}

# hooks
sub hooks {
    my $package = shift;
    my $tmp = tmpdir($package);

    if (-x 'hooks/chroot') {
	# only install it if it is not just the example file
	my @lines = lines('hooks/chroot');
	if ($#lines > 0 || $lines[0] ne 'set -e') {
	    check_allowed($package, 'hooks/chroot');
	    doit "install -D -m 755 hooks/chroot '$tmp/usr/share/$package/hooks/chroot'";
	}
    }
}

init(options => {
    "disable-restrictions" => \$dh{DISABLE_RESTRICTIONS},
});

init_macros();

foreach my $package (@{$dh{DOPACKAGES}}) {
    desktop_background($package);
    desktop_files($package);
    desktop_default_applications($package);
    desktop_default_session($package);
    unity_launchers($package);
    radio_stations($package);
    webbrowser($package);
    i18n($package);
    keyboard($package);
    icons($package);
    ubiquity_slideshow($package);
    hooks($package);
    dependencies($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
