1#!/usr/bin/perl -wT
2
3use strict;
4
5use Sys::Hostname;
6use File::Basename;
7use Getopt::Std;
8use POSIX qw(strftime);
9
10sub usage() {
11
12	die("Usage:\n"
13	    ."\tpkg-stash [-D base] [-d dir] [-g group] [-o owner] [-cfNn] filename..\n"
14	    ."\tpkg-stash [-D base] [-d dir] [-g group] [-o owner] -p\n");
15}
16
17sub stashfile($ %) {
18	my ($path, %args) = @_;
19	my ($dir, $base, $ext);
20	my ($ts, $fname);
21	my (@opts, @cmd);
22
23	($base, $dir, $ext) = fileparse($path, '\.tgz', '\.tar\.gz', '\.tbz', '\.tbz2');
24	if ($args{'nostamp'}) {
25		$ts = "";
26	} else {
27		$ts = "-ts".strftime("%Y%m%d%H%M", localtime());
28	}
29	$fname = "$base$ts$ext";
30
31	@cmd = ("install");
32	push(@cmd, '-v') if ($args{'verbose'});
33	push(@cmd, $args{'copy'}) if ($args{'copy'} ne "");
34	push(@cmd, $args{'owner'}) if ($args{'owner'} ne "");
35	push(@cmd, $args{'group'}) if ($args{'group'} ne "");
36	push(@cmd, $path, "$args{dir}/$fname");
37
38	if ($args{'noact'}) {
39		print join(' ', @cmd)."\n";
40		return 1;
41	}
42	if (system(@cmd) != 0) {
43		warn "Installing $path to $args{dir}/$fname failed: $?\n";
44	}
45	if (system('rm', $path) != 0) {
46		warn "Removing %path failed: $?\n";
47	}
48}
49
50MAIN:{
51	my %stashargs = (
52		"base"	=> "/var/backups/packages/",
53		"copy"	=> "",
54		"dir"	=> "",
55		"group"	=> "",
56		"noact"	=> 0,
57		"nostamp"	=> 0,
58		"owner"	=> "",
59		"verbose"	=> 0,
60	);
61	my $printonly = 0;
62	my %opts;
63	my $path;
64
65	getopts("CcD:d:fg:Nno:pv", \%opts) or
66		usage();
67	$stashargs{'base'} = $opts{'D'} if (defined($opts{'D'}));
68	$stashargs{'copy'} = 'c' if (defined($opts{'c'}));
69	$stashargs{'copy'} = 'C' if (defined($opts{'C'}));
70	$stashargs{'dir'} = $opts{'d'} if (defined($opts{'d'}));
71	$stashargs{'force'} = 1 if (defined($opts{'f'}));
72	$stashargs{'group'} = "-g $opts{g}" if (defined($opts{'g'}));
73	$stashargs{'nostamp'} = 1 if (defined($opts{'N'}));
74	$stashargs{'noact'} = 1 if (defined($opts{'n'}));
75	$stashargs{'owner'} = "-o $opts{o}" if (defined($opts{'o'}));
76	$stashargs{'verbose'} = 1 if (defined($opts{'v'}));
77	$printonly = 1 if (defined($opts{'p'}));
78
79	if ($stashargs{'dir'} eq "") {
80		my $hostname = hostname();
81
82		$hostname =~ s/\..*//;
83		$stashargs{'dir'} = $stashargs{'base'}.$hostname;
84	}
85
86	# Do nada?
87	if ($printonly) {
88		print $stashargs{'dir'}."\n";
89		exit(0);
90	}
91
92	# Force taint mode into submission
93	delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
94	$ENV{'PATH'} = '/bin:/usr/bin';
95
96	# Okay, process the arguments..
97	if ($#ARGV == -1) {
98		usage();
99	}
100	foreach $path (@ARGV) {
101		stashfile($path, %stashargs);
102	}
103}
104