#!/usr/bin/perl -w
#
# web-edit: shell script to spawn a new terminal, editing the file specified
#
# Meant to be invoked from Netscape upon receipt of an HTTP response
# with a specific MIME type
#
# More details:
#     http://impressive.net/people/gerald/2000/12/edit-bookmarklet.html
#
# Gerald Oskoboiny, 6 Dec 2000
#
# $Id: web-edit,v 1.13 2005/09/12 20:15:04 gerald Exp $
#

use strict;

###
# terminal: which terminal program to use
# (possibilities include: rxvt, xterm, gnome-terminal)
#
my $terminal = "gnome-terminal";

###
# termopts: extra options to pass to $terminal
#
my $termopts = "--geometry 80x40";

###
# editor: which editor program to use (or a script that calls an editor).
#
# I use eac ("edit and commit"), which is an extra little script I made
# to edit a file and then do a cvs commit afterwards:
#     http://impressive.net/people/gerald/2000/12/eac
# (on my site, the cvs commit also causes the newly committed
# file to be checked out on my remote web site)
#
my $editor = "$ENV{HOME}/bin/eac";

###
# (there is no need to change anything in this section)
#
# The first arg is a file whose content is the URI to be edited.
my $response = $ARGV[0];
my $uri = "";
if ( $response =~ m,http://, ) { # does it look like a URI?
    $uri = $response;
    $uri =~ s/^x-edit://;
}
else { # not a URI, assume it is a filename (legacy code, no longer needed?)
    open( RESPONSE, "< $response" )
	or die "error reading from response $response: $!";
    $uri = <RESPONSE>;
    close( RESPONSE ) or warn "error closing response $response: $!";
}
$uri =~ s/%23.*//;	# strip anchor fragments, if any

###
# the following statements are used to map URIs to local filenames
# on your system (if you edit multiple sites as I do, you likely
# need a custom setting for each one, as I have below)
#
my $file = $uri;
chomp( $file );
if ( $uri =~ /impressive.net/ ) {
    $file =~ s,http://[a-z\.]*impressive.net,/home/gerald/www,;
    $file =~ s,/$,/index.html,;
}
elsif ( $uri =~ /w3.org/ ) {
    $file =~ s,http://[a-z\.]*w3.org,/home/gerald/WWW,;
    $file =~ s,/$,/Overview.html,;
}
$file =~ s/^file://;	# handle file: URIs (assume they refer to local files)

###
# check if we need to add an extension to the file because the URI was generic
# (see http://www.w3.org/DesignIssues/Generic )
#
$file .= ".html" if ! -f $file && -f $file . ".html";
$file .= ".txt"  if ! -f $file && -f $file . ".txt";
$file .= ".rdf"  if ! -f $file && -f $file . ".rdf";
$file .= ".xml"  if ! -f $file && -f $file . ".xml";

###
# if your terminal program doesn't have gnome-terminal-compatible
# '--title' or '-e' options, you might need to change this:
#
system "$terminal $termopts --title $file -e '$editor $file'";

exit;

