summaryrefslogtreecommitdiff
path: root/bin/envstore
blob: fb6b87b9ec3ab16db140b0b02380387e68fab3bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/env perl
## envstore - save and load environment variables
## Copyright © 2009 by Daniel Friesel <derf@derf.homelinux.org>
## License: WTFPL <http://sam.zoy.org/wtfpl>
use strict;
use warnings;
use Simplestore;

my $store_file = "/tmp/.envstore-$>";
my %store;
my $action = shift;
my $arg = shift;
my $arg2 = shift;
my ($key, $value);

sub usage {
	exec('perldoc', '-F', $0) or die("Yo, cannot execute perldoc -F $0, so do it yourself");
}

sub check_store {
	my ($mode, $uid);
	unless (-e $store_file) {
		return(0);
	}
	($mode, $uid) = (stat($store_file))[2,4];
	$mode &= 0x00077;
	if ($uid != $<) {
		print STDERR "envstore: store file not owned by us\n";
		exit(1);
	}
	if ($mode > 0) {
		print STDERR "envstore: store file writable by group/others\n";
		exit(1);
	}
	return(1);
}

sub load_store {
	return unless check_store;
	%store = %{load($store_file) || {}};
}

sub save_store {
	umask(0077);
	save($store_file, \%store);
}

sub get_keyvalue {
	my ($key, $value) = @_;
	unless (defined($value)) {
		if (exists($ENV{$key})) {
			$value = $ENV{$key};
		} else {
			print STDERR "No such parameter: $key\n";
			exit(1);
		}
	}
	return($key, $value);
}

usage unless defined($action);
load_store;
if ($action eq 'save') {
	usage unless defined($arg);
	($key, $value) = get_keyvalue($arg, $arg2);
	$store{$key} = $value;
	save_store;
} elsif ($action eq 'eval') {
	while (($key, $value) = each(%store)) {
		$value =~ s/'/'"'"'/g;
		print "export $key='$value'\n";
	}
} elsif ($action eq 'show' or $action eq 'list') {
	while (($key, $value) = each(%store)) {
		printf("%-15s = %s\n", $key, $value);
	}
} elsif ($action eq 'rm') {
	usage unless defined($arg);
	delete($store{$arg});
	save_store;
} elsif ($action eq 'clear') {
	unlink($store_file);
} else {
	usage;
}
__END__

=head1 NAME

envstore - save and restore environment variables

=head1 SYNOPSIS

B<envstore> I<command> [ I<arguments> ]

=head1 DESCRIPTION

envstore can safe and restore environment variables, thus transferring them
between different shells.

I<command> must be one of

=over

=item B<clear>

Forget all stored variables

=item B<eval>

Produce shell code for evaluation, restoring all saved variables

=item B<save> I<variable> [I<value>]

Save I<variable> either with it's current shell value or with I<value>

=item B<show>

List saved variables in better readable format

=item B<rm> I<variable>

Remove I<variable> from store

=back