#! /usr/bin/perl
# ex:ts=8 sw=4:
# $OpenBSD: pkg_subst,v 1.3 2008/06/09 12:01:39 espie Exp $
#
# Copyright (c) 2008 Marc Espie <espie@openbsd.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# very simple script, only allows substitutions

use strict;
use warnings;
use OpenBSD::Getopt;
use OpenBSD::Subst;
use OpenBSD::Error;

my $subst = OpenBSD::Subst->new;

our $opt_c;
set_usage(
'pkg_subst [-c] [-Dvar=value ...] [file ...]');
try { 
	getopts('D:ch',
	    {'D' =>
		    sub { 
			    $subst->parse_option(shift);
		    },
	     'h' => sub {	Usage(); },
	    });
} catchall {
	Usage($_);
};

my $bak = $subst->value('BAK');
if (!defined $bak) {
	$bak = '.bak';
}

if (@ARGV == 0) {
	$subst->copy_fh2(\*STDIN, \*STDOUT);
}

while (my $src = shift) {
	my $dest;
	if ($opt_c) {
		$dest = shift or die "odd number of files";
	} else {
		$dest = $src;
		$src .= $bak;
		rename($dest, $src) or die "Can't rename $dest: $!";
	}
	$subst->copy($src, $dest);
	# copy rights as well (and owner/group if we're root)
	my ($uid, $gid, $mode) = (stat $src)[4, 5, 2];
	if ($< == 0) {
		chown $uid, $gid, $dest; # not checked
	}
	chmod $mode & 07777, $dest; # not checked
}