#!/usr/bin/perl -w
# $Id: bkp-database.in.in,v 1.4 2003/09/25 11:10:38 x99laine Exp $
# Copyright (c) 2003 Jeremy Lain

use strict;
use lib '/usr/share/bkp';

use Getopt::Std;
use Date::Format;
use Sys::Hostname;
use Bkp;

# package 
my $package = "bkp-database";

# config and options
my (%conf,%opts);


sub syntax {
   print "[ This is $package (bkp 0.5.2), a database backup utility ]\n\n",
        "Syntax:\n",
        "  $package <action> [options]\n\n",
        " Actions:\n",
        "  -a           - process all databases\n",
	"  -c <class>   - process databases of class <class>\n",
        "  -h           - this help message\n",
	"  -o <db>      - process only database <db>\n\n",
        " Options:\n",
        "  -d           - debug mode\n",
        "  -f <file>    - use <file> as config file\n",
        "  -n           - simulation mode (do not touch filesystem)\n";
}


sub init {
  if ( not getopts('dhnf:ac:o:', \%opts) or $opts{'h'}) {
    &syntax();
    exit(1);
  }

  # process options
  if ($opts{'d'}) {
    $Bkp::debug = 1;
    Bkp::dprint("Running in debug mode ...\n");
  }
  
  if ($opts{'n'}) {
    Bkp::dprint("Running in simulation mode ...\n");
  }
  
  # check the requested action
  if (!$opts{'a'} and !$opts{'c'} and !$opts{'o'}) {
    print("no action was selected\n");
    &syntax;
    exit(1);
  }

  # read config file
  if ($opts{'f'}) {
    %conf = Bkp::read_conf($opts{'f'});
  } else {
    %conf = Bkp::read_conf($Bkp::confile);
  }
}


sub main {
  &init;

  my $date = time2str("%Y-%m-%d", time);
  my $hostname = hostname;
  my $dbdir = "$conf{'savedir'}/$hostname/db";
 
  # create directory
  if (Bkp::create_dir($dbdir,$opts{'n'})) {
    print("could not create '$dbdir', bailing out!");
    exit(1);
  }

  # do the backups
  foreach my $database (@{$conf{'all'}{'databases'}}) {
    if ( ($opts{'a'}) or 
         ($opts{'c'} and ($conf{'databases'}{$database}{'class'} =~ $opts{'c'})) or
	 ($opts{'o'} and ($database =~ $opts{'o'})) ) {
      Bkp::dprint("\n* Processing database $database *\n");
      my $cmd = "mysqldump --opt --databases $database | bzip2 -9 -c > $dbdir/$database.$date.bz2";
      Bkp::dprint("running : $cmd\n");
      if (!$opts{'n'}) {
        system($cmd);
      }
    }
  }

  # erase old backups
  Bkp::dprint("** Erasing old backups **\n");
  Bkp::expire_dir($dbdir,$conf{'maxdays'}{'databases'},$opts{'n'});
}

&main();
