#!/bin/bash # This script edits the file: # /etc/mysql/mariadb.conf.d/50-server.cnf # The config file will set # the server-id to # the server-id of # the running MariaDB server. # The config file is assumed to look like # the default Debian configuration file # approximately. # MariaDB will break if the user # has set the server-id in another file. set -o pipefail set -e PATH=$(dirname "$0"):$PATH source rpc.bash use_real_config() { MARIADB_CONFIG_FILE=/etc/mysql/mariadb.conf.d/50-server.cnf } use_fake_config() { use_real_config OUR_RUNTIME_DIR=/run/hosting-tools mkdir -p "$OUR_RUNTIME_DIR" REAL_MARIADB_CONFIG_FILE=$MARIADB_CONFIG_FILE FAKE_MARIADB_CONFIG_FILE=$OUR_RUNTIME_DIR/50-server.cnf cp -i -a -T -- "$REAL_MARIADB_CONFIG_FILE" "$FAKE_MARIADB_CONFIG_FILE" MARIADB_CONFIG_FILE=$FAKE_MARIADB_CONFIG_FILE } remove_fake_config() { rm -f /run/hosting-tools/50-server.cnf } get_mariadb_server_id_from_config() { set -- 's/^ *server-id *= *([^ ]+) *$/\1/p' sed -n -E -e "$1" < "${MARIADB_CONFIG_FILE}" } valid_server_id() { case "$newid" in '' | *[^0-9]* ) false ;; * ) [ "$newid" -ge 1 ] ;; esac } set_mariadb_server_id_config() { OUR_SUFFIX='.~hosting-tools~' MARIADB_CONFIG_FILE_BACKUP=$MARIADB_CONFIG_FILE$OUR_SUFFIX newid=$1 if ! valid_server_id "$newid" then echo "Error: Invalid server-id: $newid" >&2 return 9 fi if grep -q '^ *server-id *=' "$MARIADB_CONFIG_FILE" then set -- s/'^( *server-id *= *)[^ ]+ *$'/'\1'"$newid"/ else set -- s/'^#( *server-id *= *)1 *$'/'\1'"$newid"/ fi set -- sed -E -i"${OUR_SUFFIX}" -e "$1" "$@" "$MARIADB_CONFIG_FILE" } run_server() { local BASH_RPC_REMOTE_DEST="$1" shift remote_run_function "$@" } main() { set -e set -o pipefail runtime_server_id=$(mariadb -s <<< 'select @@server_id') if false then use_fake_config else use_real_config fi config_server_id=$(get_mariadb_server_id_from_config) if [ "$runtime_server_id" = "$config_server_id" ] then printf 'Warning: %s\n' \ "server-id is already correct. Doing nothing." >&2 remove_fake_config return fi set_mariadb_server_id_config "$runtime_server_id" set +e validate_new_server_id "$runtime_server_id" r=$? interactive_show_config_change if [ "$r" = 0 ] then remove_fake_config fi return $r } interactive_show_config_change() { ( set +e diff -u --color \ "$MARIADB_CONFIG_FILE_BACKUP" \ "$MARIADB_CONFIG_FILE" [ $? = 1 ] ) } validate_new_server_id() { expected=$1 received=$(get_mariadb_server_id_from_config) if [ "$expected" = "$received" ] then printf 'Success: %s: server-id = %s\n' \ "wrote MariaDB config" \ "$received" >&2 else printf 'Error: %s: server-id = %s\n' \ "failed to write MariaDB config" \ "$received" >&2 false fi } run_server "${1:-root@localhost}" main