summaryrefslogtreecommitdiff
path: root/localdumpsql
blob: 27dcc3552d820dd570f44f55b4ac4e46000c71ea (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.3 2002-03-07 16:22:51 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_get_pw() { grep password /root/.my.cnf | awk -F= '{print $2}' | head -1 | sed 's/^ //g'; }
  48. function mysql_list_db() { echo "show databases"|mysql -uroot -p`mysql_get_pw`|grep -v '^Database$'; }
  49. function mysql_dump_db() { $mysql_bin -c --add-drop-table -uroot -p`mysql_get_pw` $1; }
  50. function postgres_valid() { [ -x $postgres_bin -a -x /usr/lib/postgresql/bin/pg_ctl ]; }
  51. 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]$'"; }
  52. function postgres_dump_db() { su -s /bin/sh postgres -c "$postgres_bin $1"; }
  53. # Exit if the directory isn't there
  54. if [ ! -d "$targetdir" ]; then
  55. echo "Directory $targetdir doesn't exist!"
  56. exit 1
  57. fi
  58. # Check for valid input
  59. for sqltype in $sqltypes; do
  60. case "$sqltype" in
  61. mysql|postgres)
  62. ;;
  63. *)
  64. usage
  65. ;;
  66. esac
  67. done
  68. for sqltype in $sqltypes; do
  69. if ${sqltype}_valid; then
  70. for db in `${sqltype}_list_db`; do
  71. targetfile=$targetdir/dump_${stamp}_${db}.${sqltype}
  72. [ -f $targetfile ] && savelog -c 3 $targetfile >/dev/null
  73. ${sqltype}_dump_db $db > $targetfile
  74. done
  75. fi
  76. done