You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.3 KiB

  1. #!/bin/bash
  2. set -eux
  3. [ -n "${DOMAIN}" ] || {
  4. echo "Error: you must set \$DOMAIN prior to running this script." >&2
  5. exit 1
  6. }
  7. [ -n "${BACKUP_SERVER}" ] || {
  8. echo "Error: you must set \$BACKUP_SERVER prior to running this script." >&2
  9. exit 1
  10. }
  11. KEY_BACKUP_ID=${KEY_BACKUP_ID:-rsync}
  12. KEY_COMMENTARY="$KEY_BACKUP_ID@$DOMAIN"
  13. MIRROR_DIR_PATH="${MIRROR_DIR_PATH:-$PWD/resources/bin/mirror-dir}"
  14. [ -e "$MIRROR_DIR_PATH" ] || {
  15. echo "Error: you must set \$MIRROR_DIR_PATH or be the root of the charm to run this script." >&2
  16. exit 1
  17. }
  18. ## rsync
  19. type -p rsync >/dev/null 2>&1 || apt-get install -y rsync </dev/null
  20. ## creating rsync user
  21. mkdir -p /var/lib/rsync
  22. getent group rsync >/dev/null ||
  23. groupadd -r rsync
  24. getent passwd rsync >/dev/null ||
  25. useradd -r rsync -d /var/lib/rsync -g rsync
  26. chown rsync:rsync /var/lib/rsync
  27. ## rsync ssh key creation
  28. if [ -e /var/lib/rsync/.ssh/id_rsa.pub ]; then
  29. ## Mainly for update of old solution
  30. content=$(cat /var/lib/rsync/.ssh/id_rsa.pub)
  31. commentary=${content##* }
  32. if [ "${commentary}" != "$KEY_COMMENTARY" ]; then
  33. echo "Updating ssh key commentary from '${commentary}' to '$KEY_COMMENTARY'" >&2
  34. sed -ri "s/ [^ ]+\$/ $KEY_COMMENTARY/" /var/lib/rsync/.ssh/id_rsa.pub
  35. fi
  36. else
  37. su -c 'ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa -q -C '"$KEY_COMMENTARY" - rsync
  38. fi
  39. dest="$BACKUP_SERVER"
  40. if [[ "$dest" == *"/"* ]]; then
  41. dest="${dest%/*}"
  42. fi
  43. if [[ "$dest" == *":"* ]]; then
  44. ssh_options+=("-p" "${dest#*:}")
  45. dest="${dest%%:*}"
  46. fi
  47. ssh-keyscan "${ssh_options[@]}" -H "${dest}" > /var/lib/rsync/.ssh/known_hosts
  48. apt-get install -y kal-shlib-{common,process,cmdline,array} </dev/null
  49. case $(awk -Wversion 2>/dev/null || awk --version) in
  50. "mawk 1.3.3"*)
  51. ## Not good, it is from 1996, and we still find it on Debian 10
  52. apt-get install -y gawk </dev/null
  53. ;;
  54. esac
  55. ln -sf "$PWD/resources/bin/mirror-dir" /usr/local/sbin/mirror-dir
  56. if ! [ -e /etc/mirror-dir/config.yml ]; then
  57. mkdir -p /etc/mirror-dir
  58. cat <<EOF > /etc/mirror-dir/config.yml
  59. default:
  60. sources:
  61. - /etc
  62. EOF
  63. fi
  64. cat <<EOF > /etc/cron.d/mirror-dir
  65. SHELL=/bin/bash
  66. PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
  67. $((RANDOM % 60)) $((RANDOM % 4))-23/4 * * * root mirror-dir backup -q -h "$DOMAIN" -d "$BACKUP_SERVER"
  68. EOF