#!/usr/bin/perl -w
# -*- Mode: perl; tab-width: 4; indent-tabs-mode: nil; -*-
#
#   Moz-Remote URL launcher for Mozilla.
#
#   Copyright (c) 2003 by L. David Baron
#
# Small part based on:
#
#   data: The data: URI kitchen
#
#   Copyright (c) 2002 by Ian Hickson
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

use strict;
use MIME::Base64;

# To configure, modify these:
my $mozilla = "/usr/bin/mozilla"; # doesn't do anything anymore
$_ = $0;
s,[^/]*$,mozilla-remote,;
my $mremote = $_;                 # The mozilla-remote file in this directory.
my $method = ",new-window";       # either "", ",new-window", or ",new-tab"

# This script takes two arguments.  The first is what to open.  The
# optional second parameter is a MIME type.  If the MIME type is
# present, then the first parameter is assumed to be a local file,
# otherwise it is assumed to be a URL.

my $url;

if ($#ARGV == 0) {

    $url = $ARGV[0];

} elsif ($#ARGV == 1) {

    my $file = $ARGV[0];
    my $type = $ARGV[1];

    -e "$file" || die "$0: File $file does not exist.\n";

    open(INFILE, "$file");
    my $content;
    while (<INFILE>) {
        $content .= $_;
    }
    $url = "data:$type;base64," . encode_base64($content, '');
    close(INFILE);

} else {
    die "usage: $0 <url>\n" .
        "       $0 <file> <mimetype>\n";
}

# system($mozilla, '-remote', "openURL($url$method)");

# code to use netscape-remote -remotepipe
pipe(READH,WRITEH);
if (fork()) {
    close(WRITEH);
    open(STDIN, "<&=" . fileno(READH));
    exec($mremote, '-remotepipe');
}
close(READH);
print WRITEH "openURL($url$method)";
close(WRITEH);
