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