-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmdl-backup
executable file
·74 lines (60 loc) · 2.29 KB
/
mdl-backup
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
#!/usr/bin/perl
# This reaches into config.php and grabs the DB details and makes it super easy to
# make and restore backups
if (!-e 'config.php'){
die "Can't find a config.php";
}
open CONF, 'config.php';
my %db = ();
foreach $line (<CONF>){
if($line =~ /(^\$CFG->db(.*?)\s.*= '(.*?)')/){
$key = $2;
$val = $3;
$db{$key} = $val;
print "Line: Key '$key' Val '$val'--- \n";
}
}
close CONF;
$restore = $ARGV[0];
if ($restore){
if($db{type} eq 'mysql' or $db{type} eq 'mysqli'){
$command = "mysql -u $db{user} --password='$db{pass}' $db{name} < $restore";
} elsif($db{type} eq 'postgres7' || $db{type} eq 'pgsql'){
$command = "export PGPASSWORD=\"$db{pass}\";\n".
"sudo -u postgres psql -h $db{host} -U postgres -c \"select pg_terminate_backend(procpid) from pg_stat_activity where datname='$db{name}'\";\n".
"sudo -u postgres psql -h $db{host} -U postgres -c 'drop database \"$db{name}\"';\n".
"sudo -u postgres createdb -h $db{host} -O $db{user} -E UTF8 $db{name};\n".
#"pg_restore -O -x -n public -U $db{user} -d $db{name} $restore;";
#"pg_restore -n public -h $db{host} -U $db{user} -d $db{name} $restore;";
"pg_restore -h $db{host} -U $db{user} -d $db{name} $restore;";
} else {
print "Don't know how to restore type: $db{type}\n";
exit;
}
print "Now doing a restore of\n";
foreach $cmd (split "\n", $command){
print "Command: $cmd\n";
system ($cmd) == 0 || die;
}
} else {
use Data::Dumper;
use Sys::Hostname;
use POSIX qw/strftime/;
$host = hostname;
$date = strftime('%d-%b-%Y-%H:%M',localtime);
#print Dumper (%db);
$backup_file = "/tmp/$host\_$db{type}_$db{host}_$db{name}_$date.sql";
if($db{type} eq 'mysql' or $db{type} eq 'mysqli'){
$command = "mysqldump --skip-lock-tables -u $db{user} --password='$db{pass}' $db{name} -r $backup_file";
} elsif($db{type} eq 'postgres7' || $db{type} eq 'pgsql'){
# This isn't terribly secure but we're generally dealing with dev boxes so no-one else should be around
$command = "export PGPASSWORD=\"$db{pass}\"; pg_dump -Fc -O $db{name} -U $db{user} -f $backup_file -h $db{host}";
} else {
print "Don't know how to backup type: $db{type}\n";
exit;
}
print "Command: $command\n";
system ($command) == 0 || die;
print "Copy the backup back to your local box:\n";
print " scp $host\:$backup_file /tmp\n";
}