summaryrefslogtreecommitdiff
path: root/replicate-db
blob: 8244ff7cd68497d394a2ab2ac0fb0f3d73dbbba3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/bin/bash

set -e

if [ -d '/var/lib/mysql' ]; then
  read -p 'mariadb seems to be installed already - I will remove it first.' -r s
  if [ -n "${s}" ]; then
    echo 'Aborted.'
    exit
  fi
  sudo systemctl stop mysqld || true
  sudo systemctl disable mysqld || true
  sudo pacman -Rs mariadb || true
  sudo rm -rf --one-file-system '/var/lib/mysql' '/etc/mysql'
fi

read -p 'enter new root-pw: ' -s -r root_pw
printf '\n'
read -p 'enter replikat-pw: ' -s -r replikat_pw
printf '\n'

sudo pacman -S --noconfirm mariadb

# set up mariadb
sudo mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
sudo sed -i '
  /^\s*\[mysqld]\s*$/ a group_concat_max_len = 4096 \
server-id = '"$RANDOM"' \
skip-networking
' '/etc/my.cnf.d/server.cnf'

sudo systemctl start mysqld
sudo systemctl enable mysqld

printf '\n\n\n%s\n%s\n\n\n\n\n' "${root_pw}" "${root_pw}" | \
  sudo mysql_secure_installation

tmp_file=$(mktemp)
trap 'rm "${tmp_file}"' EXIT

database_dump=$(
  ssh master@10.100.10.1 '
    cd /data/backup/mysql;
    ls -t
  ' \
  | grep -xm1 'database-.*\.xz'
)

find /tmp \
  -maxdepth 1 \
  -type f \
  -name "${database_dump}" \
  -exec rsync -avP {} "${tmp_file}" \;

rsync -avP \
  "master@10.100.10.1:/data/backup/mysql/${database_dump}" \
  "${tmp_file}"

{
  printf 'SHOW SLAVE STATUS;\n'
  printf "CREATE USER 'webserver'@'localhost' IDENTIFIED BY 'empty';\n" \
  printf "GRANT USAGE ON *.* TO 'webserver'@'localhost' IDENTIFIED BY 'empty';\n"
  printf "GRANT REPLICATION CLIENT ON *.* TO 'webserver'@'localhost';\n"
  printf 'GRANT %s ON buildmaster.* TO '"'"'webserver'"'"'@'"'"'localhost'"'"';\n' \
    'CREATE TEMPORARY TABLES'  \
    'SELECT' \
    'SHOW VIEW'
  printf "CHANGE MASTER TO MASTER_HOST='%s', MASTER_PORT=%s, MASTER_USER='%s', MASTER_PASSWORD='%s';\n" \
    '10.100.10.1' \
    3306 \
    'replikat' \
    "${replikat_pw}"
  pv "${tmp_file}" | xzcat
  xzgrep -- '^-- CHANGE MASTER TO ' "${tmp_file}" | \
    sed 's/^-- //'
  printf 'START SLAVE;\n'
  printf 'SHOW SLAVE STATUS;\n'
} | \
  mysql -u root -p"${root_pw}"

printf '\n\nAll set up successfully.\n'