summaryrefslogtreecommitdiff
path: root/localdumpsql
blob: 64b90b9561d1da11fde0d163e6c45105f61fcc6c (plain)
  1. #!/bin/bash
  2. #
  3. # /usr/local/sbin/localdumpsql
  4. # Copyright 2001-2002 Jonas Smedegaard <dr@jones.dk>
  5. #
  6. # $Id: localdumpsql,v 1.4 2003-05-20 00:22:30 jonas Exp $
  7. #
  8. # MySQL/PostgreSQL maintenance script
  9. #
  10. # Automagically runs when symlinked to /etc/cron.{daily,weekly,monthly}/
  11. #
  12. # halt on errors
  13. set -e
  14. function usage() {
  15. echo "Usage: `basename $0` daily|weekly|monthly|<whatever> [mysql|postgres]"
  16. echo " If sqltype is missing, all are attempted"
  17. echo " Tip: Automagically runs when symlinked to /etc/cron.{daily,weekly,monthly}/"
  18. exit 1
  19. }
  20. # automagically configure when run from cron dirs
  21. case `dirname $0` in
  22. /etc/cron.daily)
  23. stamp=daily
  24. ;;
  25. /etc/cron.weekly)
  26. stamp=weekly
  27. ;;
  28. /etc/cron.monthly)
  29. stamp=monthly
  30. ;;
  31. *)
  32. if [ $# -lt 1 -o $# -gt 2 ]; then
  33. usage
  34. fi
  35. stamp=$1
  36. sqltypes=$2
  37. ;;
  38. esac
  39. # Default is all sqltypes
  40. [ -z $sqltypes ] && sqltypes="mysql postgres"
  41. # Define paths
  42. targetdir=/var/local/backups/localhost
  43. mysql_bin=/usr/bin/mysqldump
  44. postgres_bin=/usr/lib/postgresql/bin/pg_dump
  45. # Define routines
  46. function mysql_valid() { [ -x $mysql_bin ]; }
  47. function mysql_list_db() { mysql -uroot -e 'show databases' | grep -v '^Database$'; }
  48. function mysql_dump_db() { $mysql_bin -c --add-drop-table -uroot $1; }
  49. function postgres_valid() { [ -x $postgres_bin -a -x /usr/lib/postgresql/bin/pg_ctl ]; }
  50. function postgres_list_db() { su -s /bin/sh postgres -c "/usr/bin/psql -t -c 'select datname from pg_database order by datname' -d template1 | sed -e 's/ //' | grep -v '^template[01]$'"; }
  51. function postgres_dump_db() { su -s /bin/sh postgres -c "$postgres_bin $1"; }
  52. # Exit if the directory isn't there
  53. if [ ! -d "$targetdir" ]; then
  54. echo "Directory $targetdir doesn't exist!"
  55. exit 1
  56. fi
  57. # Check for valid input
  58. for sqltype in $sqltypes; do
  59. case "$sqltype" in
  60. mysql|postgres)
  61. ;;
  62. *)
  63. usage
  64. ;;
  65. esac
  66. done
  67. for sqltype in $sqltypes; do
  68. if ${sqltype}_valid; then
  69. for db in `${sqltype}_list_db`; do
  70. targetfile=$targetdir/dump_${stamp}_${db}.${sqltype}
  71. [ -f $targetfile ] && savelog -c 3 $targetfile >/dev/null
  72. ${sqltype}_dump_db $db > $targetfile
  73. done
  74. fi
  75. done