#!/usr/local/bin/perl
#
# make_isp = catalog configurator for ISP
#
# Copyright 1996 by Michael J. Heins <mikeh@iac.net>
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.

$VendRoot = '/home/mvend203';

# Set this to '' if your system doesn't support mkdir -p
$mkdirgood = '-p';

## END CONFIGURABLE VARIABLES

$prog = $0;
$basefile = "$prog.cfg";
$| = 1;

use File::Find;

if($ARGV[0] eq '-r') {
	shift @ARGV;
	$Reconfigure = 1;
}

if($ARGV[0] eq '-f') {
	shift @ARGV;
	$Force = 1;
}

$configfile = shift || die "usage: makecat [-r] <configfile>\n";

$configname = $configfile;
$configname =~ s:.*/::;
$configname =~ s:\.[^/]*$::;

unless ($configfile =~ /\.cat$/) {
	$configfile .= '.cat';
}

sub can_do_suid {
	my $file = "tmp$$.fil";
	my $status;

	open(TEMPFILE,">$file");
	close TEMPFILE;
	eval { chmod 04755, $file; $@ = ''};
	$status = $@ ? 0 : 1;
	unlink $file;
	return $status;
}

sub get_id {
    my $file = -f "$VendRoot/error.log"
                ? "$VendRoot/error.log" : '';
    return '' unless $file;
    my ($name, $group);

    my($uid) = (stat($file))[4];
    $name = (getpwuid($uid))[0];
    return $name;
}

sub get_ids {
	my $file = "tmp$$.fil";
	my ($name, $group);

	open(TEMPFILE,">$file");
	close TEMPFILE;
	my($uid,$gid) = (stat($file))[4,5];
	unlink $file;
	$name = (getpwuid($uid))[0];
	$group = (getgrgid($gid))[0];
	return ($name,$group);
}
	

sub prompt {
    my($pr) = shift || '? ';
    my($def) = shift;
    my $ans = '';

    print $pr;
    print "[$def] " if $def;
    unless($Force ||= 0) {
		chop($ans = <STDIN>);
	}
	else {
		print "\n";
	}
    $ans ? $ans : $def;
}

sub do_msg {
	my ($msg, $size) = @_;
	$size = 60 unless defined $size;
	my $len = length $msg;
	
	return "$msg.." if ($len + 2) >= $size;
	$msg .= '.' x ($size - $len);
	return $msg;
}
	

sub is_yes {
    return( defined($_[0]) && ($_[0] =~ /^[yt1]/i));
}

print <<EOF ;

make_isp - MiniVend catalog installation for:

           Internet Service Providers
           Dedicated Web servers

*** We will be making a catalog named '$configname'. ***

EOF


if ($< != 0) {
    print <<EOF ;

This demo configuration often requires root permissions, as
it needs to copy things to directories presumably owned by
others, and change ownership and permissions of many files.

If you will be operating only on directories owned by the
user you are running this as, you will be able to do everything.

You are not root at this time. 

EOF
    $yes = prompt("Continue? ", 'n');
    exit 2 unless is_yes($yes);
    print "\nOK, we will try to muddle along.\n\n";
    $isroot = 0;
    
}
else { $isroot = 1; }

%Prefix = (
	vendroot     =>  $VendRoot,
	basedir      =>  '/home/USER_NAME/minivend',
	minivenduser =>  '',
	minivendgroup=>  sub {
						my $gid = (getpwnam($Config{minivenduser}))[3];
						(getgrgid($gid))[0];
					 },
    documentroot =>  '/home/USER_NAME/www',
	cgidir       =>  '/usr/local/etc/httpd/cgi-bin',
	cgibase      =>  '/cgi-bin',
	demotype     =>  'simple',
	servername   =>  '',
    catuser      =>  sub { $isroot ? '' : $Config{'minivenduser'} },
    mailorderto  =>  sub {  if($Config{servername} =~ s:(/~[^/]+)$:: ) {
								$Tilde = $1;
							}
							$Config{catuser} },
	catroot      =>  sub { $Config{basedir} . "/" . $configname },
	cgiurl       =>  sub { my $url = '';
							if ($Config{cgibase} eq '') {
								$url =	$Tilde if defined $Tilde;
								$url .=	'/' .
										$configname .
										'.cgi';
							}
							else {
								$url .= $Config{cgibase} . '/' . $configname;
							}
							$url;
						  },
	imagedir     =>  sub { $Config{samplehtml} . '/' . 'images' },
	imageurl     =>  sub {  my $url = '';
	                        if(defined $Tilde) {
								$url = $Tilde;
							}
							$url .= '/' . $Config{sampledir} . '/' . 'images';
							$url;
						},
	sampledir    =>  $configname,
	samplehtml   =>  sub { $Config{documentroot} . '/' . $Config{sampledir} },

);

unless($isroot) {
	@Prefix{qw(minivenduser minivendgroup)} = get_ids();
	$Prefix{catuser} = $Prefix{minivenduser};
	$Prefix{basedir} = "$ENV{HOME}/catalogs";
	$Prefix{cgidir} = "$ENV{HOME}/cgi-bin";
	$Prefix{cgibase} = "";
	$Prefix{documentroot} = "$ENV{HOME}/public_html";
}
 
%LegalBase = qw(

	basedir         1
	cgidir          1
	cgibase         1
	documentroot    1
	minivendgroup	1
	minivenduser    1
	vendroot        1

);

$HasBase = 0;
if(-f $basefile) {
	@base = `cat $basefile`; 
    if(@base) {
		$HasBase = 1
			unless $Reconfigure;
	}
	else {
		warn "\nMaster configuration file empty.\n";
	}
	print "Using master configuration file $basefile.\n";
}


for(@base) {
	next if /^\s*#/;
	next if /^\s*$/;
	chomp;
	s/\s+$//;
	($param, $val) = split(/\s+/, $_, 2);
	$param = lc $param;
	(warn "Unknown parameter $param in $basefile, skipping.\n", next)
		unless defined $LegalBase{$param};
	$Prefix{$param} = $val;
}
 
if(-f $configfile) {
	@config = `cat $configfile`; 
	warn "\nConfig file empty.\n" 
        unless @config;
}
else {
	print "New configuration '$configname',\nwill create file $configfile.\n";
}
 
%MacroString = qw(

	__MVC_CGIURL		cgiurl
	__MVC_CGIDIR		cgidir
	__MVC_MAILORDERTO	mailorderto
	__MVC_IMAGEURL		imageurl
	__MVC_SAMPLEURL		sampleurl
	__MVC_SERVERNAME	servername

);
 
%Pretty = qw(

	basedir         BaseDir
	catuser			CatUser
	cgibase         CgiBase
	cgidir          CgiDir
	cgiurl          CgiUrl
	demotype        DemoType
	documentroot    DocumentRoot
	imagedir        ImageDir
	imageurl        ImageUrl
	mailorderto     MailOrderTo
	minivenduser	MiniVendUser
	minivendgroup	MiniVendGroup
	samplehtml      SampleHtml
	sampledir       SampleDir
	sampleurl       SampleUrl
	servername      ServerName
	catroot         CatRoot
	vendroot        VendRoot

);
 
 
%Desc = (

	basedir    =>  <<EOF,
# A prefix to include on non-HTML directories, for defaults. If you use
# the string USER_NAME, the name of the catalog user will be substituted.
# If you use the string SERVER_NAME, the name of the virtual domain
# will be substituted.
# 
# You will be given a chance to redefine the directories when you
# build the catalog, this is only for defaults.
#
EOF
	catuser    =>  <<EOF,
#
# The user name the catalog will be owned by.
#
EOF
	cgibase    =>  <<EOF,
#
# The URL-style location of the normal CGI directory.
# Only used to set the default for the CgiUrl setting.
#
# http://www.virtual.com/cgi-bin/prog
#                       ^^^^^^^^
#
# You will be given a chance to redefine the URL when you
# build the catalog, this is only for defaults.
EOF
	cgidir     =>  <<EOF,
# The location of the normal CGI directory. This is a UNIX
# file name, not a script alias.
#
# Apache default:  /usr/local/apache/cgi-bin
# NCSA default:    /usr/local/etc/httpd/cgi-bin
#
EOF
	cgiurl     =>  <<EOF,
# The URL location of the CGI program, without the http://
# or server name.
#
# http://www.virtual.com/cgi-bin/prog
#                       ^^^^^^^^^^^^^
EOF
	demotype   =>  <<EOF,
# The type of demo, sample, simple, or one that you have defined.
# It should be a subdirectory of the MiniVend root, but you will
# be given a chance to specify another if it isn't found.  If it is 
# found, it will be used.
#
EOF
	documentroot    =>  <<EOF,
# The base directory for HTML for most catalogs, the DocumentRoot.
# This is a UNIX file name, not a URL.  If you use the string
# USER_NAME, the name of the catalog user will be substituted.
# If you use the string SERVER_NAME, the name of the virtual domain
# will be substituted.
#
# Apache default:  /usr/local/apache/htdocs
# NCSA default:    /usr/local/etc/httpd/htdocs
#
EOF
	mailorderto  =>  <<EOF,
# The email address where orders for this catalog should go.
# To have a secure catalog, either this should be a local user name and
# not go over the Internet -- or use the PGP option.
#
EOF
	minivenduser  =>  <<EOF,
# The user name the MiniVend server runs under on this machine.
# This CANNOT be root -- you might define a user 'minivend'. If you
# are not root as you install this catalog, you might have trouble
# with write permissions.
#
EOF
	minivendgroup    =>  <<EOF,
# The group name the server-owned files should be set to.  This is
# important if the user is to be able to read and edit their own
# catalog configuration. It is suggested that the MiniVend
# user be added to the group that the user already is in. Set
# to the empty string if all files should be owned by the
# MiniVend user.
# 
# For ISPs who make a group for each user, adding the MiniVend
# user to that group and setting the group permissions to write
# works well. In fact, that is the default for this installation.
#
EOF
	imagedir   =>  <<EOF,
# Where the sample images should be installed. A UNIX file
# name, not a URL.
#
EOF
	imageurl   =>  <<EOF,
# The URL base for the sample images. Sets the ImageDir
# directive in the catalog configuration file. This is a URL
# fragment, not a directory or file name.
#
#         <IMG SRC="/sample/images/icon.gif">
#                   ^^^^^^^^^^^^^^
#
EOF
	samplehtml =>  <<EOF,
# Where the sample HTML files (not MiniVend pages) should be
# installed. There is a difference.  Usually a subdirectory of
# the user's HTML directory.
#
EOF
	sampleurl  =>  <<EOF,
# Our guess as to the URL to run this catalog, used for the
# client-pull screens and an informational message, not prompted for.
#
EOF
	servername =>  <<EOF,
# The server name, something like: www.company.com
#
EOF
	catroot   =>  <<EOF,
# Where the MiniVend files for this catalog will go, pages,
# products, config and all.  This should not be in HTML document
# space!  Usually a directory named 'minivend' off of the user's
# home works well. Images and static HTML files somewhere in HTML
# document space, and will be prompted for later.
#
EOF

	vendroot  =>  <<EOF,
# The directory where MiniVend is installed, or a suitable
# substitute containing a valid minivend.cfg file, the vlink
# executable in the src/ subdirectory, and some demo page trees.
#
EOF

);
 
 
%LegalConfig = qw(

	cgidir          1
	cgiurl          1
	catuser		  	1
	demotype		1	
	documentroot    1
	imagedir        1
	imageurl        1
	mailorderto  	1
	minivenduser	1
	minivendgroup	1
	samplehtml      1
	sampledir       1
	sampleurl       1
	servername      1
	catroot         1

);

@AskBase = qw( vendroot basedir minivenduser minivendgroup
				documentroot cgidir cgibase );

@AskConfig = qw(	demotype servername minivenduser minivendgroup
					catuser mailorderto catroot cgidir cgiurl
					documentroot samplehtml imagedir imageurl);

for(@AskBase, 'sampledir') {
	if(! ref $Prefix{$_}) {
		$Config{$_} = $Prefix{$_};
	}
	else {
		$Config{$_} = &{$Prefix{$_}};
	}
}

for(@config) {
	next if /^\s*#/;
	next if /^\s*$/;
	chomp;
	s/\s+$//;
	($param, $val) = split(/\s+/, $_, 2);
	$param = lc $param;
	(warn "Unknown parameter $param in $configfile, skipping.\n", next)
		unless defined $LegalConfig{$param};
	$Initial{$param} = $val;
}

$checkconfig = 0;
$checkmaster = 0;

print <<EOF unless $HasBase || $Reconfigure;
Since there was no master configuration file, we will ask
the questions we need answers to.  You will be given an opportunity
to save the file, and then we will continue the configuration.

EOF

for(@AskBase) {
	last if $HasBase;
	$val = $Initial{$_} || $Config{$_};
	$Config{$_} = prompt ("\n$Desc{$_}\n\n$Pretty{$_}? ", $val);
	$checkmaster += ($Config{$_} ne $val and defined $LegalBase{$_});
}

WRITEMASTER: {
	last WRITEMASTER unless $checkmaster;
	$yes = is_yes(prompt ("\nSave master configuration? ", 'y'));
	if($yes) {
		open(OUT, ">$basefile") or die "Couldn't write $basefile: $!\n";
		for(@AskBase) {
			print OUT $Desc{$_};
			printf OUT "%-16s%s\n\n", $Pretty{$_}, $Config{$_};
		}
		close OUT;
	}
}

unless ($HasBase) {
	print "Continuing the configuration with the new defaults.\n\n";
	exec "$prog $configfile";
}
	

for(@AskConfig) {
	if(! ref $Prefix{$_}) {
		$Config{$_} = $Prefix{$_}
			unless defined $Config{$_};
	}
	else {
		$Config{$_} = &{$Prefix{$_}}
			unless defined $Config{$_};
	}
	$val = $Initial{$_} || $Config{$_};
	$val =~ s/USER_NAME/$Config{catuser}/g
		if (defined $Config{catuser} and $Config{catuser});
	$val =~ s/SERVER_NAME/$Config{servername}/g
		if (defined $Config{servername} and $Config{servername});
	$Config{$_} = prompt ("\n$Desc{$_}\n\n$Pretty{$_}? ", $val);
	$Prefix{$_} = $Config{$_};
	$checkconfig += ($Config{$_} ne $val and defined $LegalConfig{$_});
}

WRITECONFIG: {
	last WRITECONFIG unless $checkconfig;
	$yes = is_yes(prompt ("\nSave demo configuration '$configname' to $configfile? ", 'y'));
	if($yes) {
		open(OUT, ">$configfile") or die "Couldn't write $configfile: $!\n";
		for(@AskConfig) {
			print OUT $Desc{$_};
			printf OUT "%-16s%s\n\n", $Pretty{$_},
									ref $Config{$_}
									? &{$Config{$_}}
									: $Config{$_}		;
		}
		close OUT;
	}
}

# Try and get the URL we will use to access the catalog
GUESS: {

	my $tempurl;
    $guessdir = $Config{samplehtml};

    unless($guessdir =~ s/^$Config{documentroot}//) {
        print <<EOF;
\a
The specified HTML directory, $Config{samplehtml},
is not a subdirectory of DocumentRoot. This will make it
hard for us to guess the URL needed to access pages from
the catalog. Please re-specify your HTML document root.

# The base directory for HTML for the catalog, the DocumentRoot.
# This is a UNIX file name, not a URL.

EOF
        $val = '';
        $Config{documentroot} = prompt ("\n$Pretty{documentroot}? ", '');
        redo GUESS;
    }

    $guessdir =~ s:^/+::;
    $guessdir = "$Tilde/$guessdir" if defined $Tilde;
    $guessdir =~ s:^/+::;
    $tempurl = "http://$Config{servername}/$guessdir";
    if (defined $Config{sampleurl} and $Config{sampleurl} ne $tempurl) {
		print <<EOF;

We were given a previous value for the URL that will run the catalog
(from the catalog configuration file $configfile):

    $Config{sampleurl}

This conflicts with what we guess from what you have just
entered:

   	$tempurl

EOF

	$tempurl  = prompt ("\nPlease re-enter or confirm: ",
						"http://$Config{servername}/$guessdir");

	}

	$Config{sampleurl} = $tempurl;

}

$mvuid = getpwnam($Config{minivenduser});
unless (defined $mvuid) {
	die "$Config{minivenduser} is not a valid user name on this machine.\n";
}

if($isroot) {
	chown ($mvuid, $mvgid, $configfile)
		or warn "\nCouldn't set ownership of $configfile: $!\n";
}

if ($Config{minivendgroup}) {
	$mvgid = getgrnam($Config{minivendgroup});
	unless (defined $mvgid) {
		die "$Config{minivendgroup} is not a valid group name on this machine.\n";
	}
}
else {
	$mvgid = (getpwnam($Config{minivenduser}))[3];
}

($catuid,$catgid) = (getpwnam($Config{catuser}))[2,3];
unless (defined $catuid) {
	die "$Config{catuser} is not a valid user name on this machine.\n";
}

# Now change to the directory defined as VendRoot
chdir $Config{vendroot}
	or die "Couldn't change directory to $Config{vendroot}: $!\n";


$warn = 0;
$msg = q# supposed to be a directory, not a file. Can't continue.#;
for ( $Config{catroot}, $Config{samplehtml}, $Config{imagedir} ) {
	next unless -f $_;
	warn "$_ $msg\n";
	$warn++;
}
die "\n" if $warn;

die("Couldn't find vlink executable.\n")
    unless (-x 'src/vlink' and -f _);

$warn = 0;
print do_msg("Checking directories");

$msg = q#directory exists!#;
for($Config{catroot}, $Config{samplehtml}) {
	next unless -d $_;
	warn "\n$_: $msg\n";
	$warn++;
}

if($warn) {
	$ask = prompt "The above directories already exist. Overwrite files? ", 'n';
	exit 2 unless is_yes($ask);
}

for($Config{catroot}, $Config{samplehtml}, $Config{imagedir}) {
	next if -d $_;
	$warn++;
}

if($warn) {
	for(qw(catroot samplehtml imagedir)) {
		$dir = $Config{$_};
		(warn "\n$_ is empty, skipping.\n", next)
			unless $dir =~ /\S/;
		unless(-d $dir) {
			system "mkdir $mkdirgood $dir";
			if($?) {
				die "Couldn't make directory $dir: $!\n";
			}
		}
		if($isroot) {
			chown ($mvuid, $mvgid, $dir)
				or die "Couldn't change ownership of $dir: $!\n";
		}
	}
}

for(qw(catroot samplehtml imagedir)) {
		$dir = $Config{$_};
		die "Directory $dir not writable, can't continue.\n"
			unless -w $dir;
}
print "done.\n";

# Now change to the directory defined as VendRoot if the checks
# have left us elsewhere
chdir $Config{vendroot}
	or die "Couldn't change directory to $Config{vendroot}: $!\n";

print do_msg("Copying demo files");
unless (-d $Config{'demotype'}) {
	$dir = prompt("\nNo $Config{'demotype'} directory is present, where should\n" .
			      "the files come from? ", '');
}
else {
	$dir = $Config{'demotype'};
}
chdir $dir || die "Couldn't change directory to $dir: $!\n";

system "tar -cf - * | (cd $Config{catroot}; tar -xf -)";

if($?) {
	die <<EOF
There were errors in copying the demo files.  Cannot
continue.  Check to see if permissions are correct, and
that the 'tar' program is available.

EOF
}

system "cp $VendRoot/src/vlink $Config{catroot}";

if($?) {
	die "Couldn't copy vlink executable: $!\n";
}

print "done.\n";


chdir $Config{catroot} 
 	|| die "Couldn't change directory to $Config{catroot}: $!\n";


%Mfile = ( qw(
                catalog.cfg     1
                error.log       1
                etc             1
                products        1
                products.db     1
                products.gdbm   1
                session         1
                session.db      1
                session.gdbm    1
                session.lock    1
            ) );

sub wanted {

	my ($mode,$file);
	$file = $_;
	my $name = $File::Find::name;
	EDIT: {
     	return if        (-l $file);

	# Ugly, but necessary on BSDI
	$File::Find::prune = 1 if -f _;

        last EDIT unless (-f _);
        last EDIT unless (-T _);
  
		open(IN, $file) or die "Couldn't open $name: $!\n";
		open(OUT, ">$file.new") or die "Couldn't create $name.new: $!\n";
		while(<IN>) {
			s/(__MVC_[A-Z0-9]+)/$Config{$MacroString{$1}}/g;
			print OUT $_;
		}
		close OUT;
		close IN;
		unlink ($file)
			or die "Couldn't unlink $name: $!\n";
		rename ("$file.new", $file)
			or die "Couldn't rename $name.new to $name: $!\n";
	}
	if(defined $Mfile{$file} or $file =~ /\.(gdbm|asc|csv|db)$/) {
		if($isroot) {
			chown ($mvuid, $mvgid, $file)
				or die "\nCouldn't set ownership of $name: $!\n";
		}
		$mode = (stat($file))[2];
		$mode |= 16;
		chmod ($mode, $file)
			or die "\nCouldn't set permissions on $name: $!\n";
			
	}
	else {
		chmod(0755, $file) if $file =~ /reconfig$/;
		if($isroot) {
			chown ($catuid, $catgid, $file)
				or die "\nCouldn't set ownership on $name: $!\n";
		}
	}
}
	
	$File::Find::dont_use_nlink = 1;
	File::Find::find(\&wanted, $Config{catroot});

	if($isroot) {
		chown ($mvuid, $mvgid, $Config{catroot})
			or warn "\nCouldn't set ownership of $Config{catroot}: $!\n";
	}

	$cginame = $Config{cgiurl};
	$cginame =~ s:.*/::;
	$cginame = "$Config{cgidir}/$cginame";

	print do_msg("Moving vlink program to $cginame");
	
	system "mv $Config{catroot}/vlink $cginame";
	if($?) {
		die "Couldn't move vlink executable to $cginame: $!\n";
	}

	if($isroot) {
		chown ($mvuid, $mvgid, $cginame)
			or die "\nCouldn't set ownership of $cginame: $!\n";
	}

	unless ($isroot or can_do_suid()) {
		print <<EOF;

My test indicates you can't change vlink to SUID mode.
This will cause big problems -- you can make MiniVend work anyway
by changing the ReadPermission and WritePermission directives in
all of your catalogs to 'world', but this is not secure. If you can,
you should run this as root, or su to root and do:

    chmod 4755 $cginame

EOF
		$ask = prompt("Continue? ", 'n');
		exit 2 unless is_yes($ask);
	}
	chmod 04755, $cginame
		or warn "\nCouldn't set permissions on $cginame: $!\n";

	print "done.\n";

	
	print do_msg("Moving HTML files to $Config{samplehtml}");
	system "mv html/* $Config{samplehtml}";
	if($?) {
		die "Couldn't move vlink executable to $cginame: $!\n";
	}
	rmdir 'html'
		or die "Couldn't remove HTML directory: $!\n";
	print "done.\n";

	print do_msg("Moving image files to $Config{imagedir}");
	system "mv images/* $Config{imagedir}";
	if($?) {
		die "Couldn't move image files to $Config{imagedir}: $!\n";
	}
	if($isroot) {
		opendir(CHGIT,$Config{imagedir})
			or die "couldn't open $Config{imagedir}: $!\n";
        my (@files) = grep !/^\./, readdir CHGIT;
		closedir CHGIT;
		for(@files) {
			chown ($catuid, $catgid, "$Config{imagedir}/$_")
				or die "Couldn't chown image files in $Config{imagedir}: $!\n";
		}
	}
	rmdir 'images'
		or die "Couldn't remove image directory: $!\n";
	print "done.\n";

	chdir $VendRoot
		or die "Couldn't change directory to $VendRoot: $!\n";

	$yes = prompt "Add catalog to minivend.cfg? ", 'y';

	if( is_yes($yes) ) {
		my ($newcfgline, $mark, @out);
		my ($tmpfile) = "minivend.cfg.$$";
		rename ("minivend.cfg", $tmpfile)
			or die "Couldn't rename minivend.cfg: $!\n";
		open(CFG, $tmpfile)
			or die "Couldn't open $tmpfile: $!\n";
		$newcfgline = sprintf "%-19s %s %s %s\n", 'Catalog',
				$configname, $Config{catroot}, $Config{cgiurl};
		while(<CFG>) {
			$mark = $. if /^#?\s*catalog\s+/i;
			warn "\nDeleting old configuration $configname.\n"
				if s/^(\s*catalog\s+$configname\s+)/#$1/io;
			push @out, $_;
		}
		close CFG;
		open(NEWCFG, ">minivend.cfg")
			or die "\nCouldn't write minivend.cfg: $!\n";
		if (defined $mark) {
			print NEWCFG @out[0..$mark-1];
			print NEWCFG $newcfgline;
			print NEWCFG @out[$mark..$#out];
		}
		else { 
			$newconfig = 1;
			warn "\nNo catalog previously defined. Adding $configname at top.\n";
			print NEWCFG $newcfgline;
			print NEWCFG @out;
		}
		close NEWCFG || die "close: $!\n";
		unlink $tmpfile;
		if($isroot) {
			chown ($mvuid, $mvgid, 'minivend.cfg')
				or warn "Couldn't set ownership of 'minivend.cfg': $!\n";
		}
	}
	else {
		my $newcfgline = sprintf "%-19s %s %s %s\n", 'Catalog',
				$configname, $Config{catroot}, $Config{cgiurl};
		print <<EOF;

-----------------------------------------------------------------
-----------------------------------------------------------------
You will need to add the following line to your minivend.cfg file
to activate the catalog.

$newcfgline
-----------------------------------------------------------------
-----------------------------------------------------------------

EOF
	}

	print <<EOF;

Done with configuration. If my reading of your input is correct, you
and your user should be able to access the demo catalog with the
following URL:

	$Config{sampleurl}

In any case, you should get direct access at:

	http://$Config{servername}$Config{cgiurl}

That is, after you START or RESTART the MiniVend server.  8-)
It is best done with:

	$Config{vendroot}/bin/restart

EOF
	print "Good luck with MiniVend 2.0!\n" if defined $newconfig;

