#!/usr/bin/env bash
# Switches a Squirro RPM installation from the PyMySQL database driver to the MariaDB
# connector, which Squirro has used since 3.10.2. The upgrade to 3.17.4 installs Squirro
# from new Python 3.14 packages, and none of them pulls in PyMySQL, so services still
# configured with mysql+pymysql:// don't start after it.
#
# Run it as root on the Squirro host, before or after the upgrade. It replaces
# mysql+pymysql:// with mysql+mariadbconnector:// in /etc/squirro/*.ini, keeps a copy of
# every file it changes under /root, and restarts the Squirro services. It can't read
# encrypted database settings, so it lists them for you to check. Running it again
# changes nothing. It never prints connection strings, which hold passwords.
#
# Usage: squirro-use-mariadb-connector.sh [--dry-run] [--no-restart]
#   --dry-run     list the files that would change, and change nothing
#   --no-restart  switch the files but leave restarting the services to you
#
# Exit status: 0 when done or nothing to do, 1 when something needs a person.
set -euo pipefail

CONFIG_DIR=/etc/squirro
OLD='mysql+pymysql://'
NEW='mysql+mariadbconnector://'
# OLD on a line that isn't a comment.
IN_USE='^[[:space:]]*([^#;[:space:]].*)?mysql\+pymysql://'
# An encrypted URL hides its driver, so this script can't see or change it.
ENCRYPTED='^[[:space:]]*db[[:space:]]*[=:][[:space:]]*CK_[A-Z]+::'
dry_run=0
restart=1

for arg in "$@"; do
    case "$arg" in
        --dry-run) dry_run=1 ;;
        --no-restart) restart=0 ;;
        -h | --help) sed -n '2,17p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
        *) echo "Unknown option: $arg (see --help)" >&2; exit 1 ;;
    esac
done

if [ "$(id -u)" -ne 0 ]; then
    echo "Run this as root." >&2
    exit 1
fi

mapfile -t files < <(grep -l -E "$IN_USE" "$CONFIG_DIR"/*.ini || true)
mapfile -t encrypted < <(grep -l -i -E "$ENCRYPTED" "$CONFIG_DIR"/*.ini || true)
if [ ${#encrypted[@]} -gt 0 ]; then
    echo "Encrypted database settings, which this script can't read:"
    printf '  %s\n' "${encrypted[@]}"
fi

# Ends a run that changed what it could: exit 1 if encrypted settings are left to check.
finish() {
    if [ ${#encrypted[@]} -gt 0 ]; then
        echo "Check the encrypted settings listed above by hand: they must use $NEW." >&2
        exit 1
    fi
    exit 0
}

if [ ${#files[@]} -eq 0 ]; then
    echo "No file in $CONFIG_DIR uses $OLD. Nothing to do."
    finish
fi
echo "Using $OLD:"
printf '  %s\n' "${files[@]}"

venv=/opt/squirro/virtualenv314
[ -x "$venv/bin/python" ] || venv=/opt/squirro/virtualenv311
if ! "$venv/bin/python" -c 'import mariadb' 2>/dev/null; then
    echo "The MariaDB connector can't be imported in $venv, so nothing was changed." >&2
    echo "It needs Squirro 3.10.2 or later. To see why: $venv/bin/python -c 'import mariadb'" >&2
    exit 1
fi

if [ "$dry_run" -eq 1 ]; then
    echo "Dry run: nothing changed."
    finish
fi

backup=/root/squirro-pymysql-backup-$(date +%Y%m%d-%H%M%S)
mkdir -m 700 "$backup"
cp -p "${files[@]}" "$backup/"
sed -i -E "/^[[:space:]]*[#;]/!s#mysql\+pymysql://#$NEW#g" "${files[@]}"
if command -v restorecon > /dev/null; then
    restorecon "${files[@]}"
fi
if grep -q -E "$IN_USE" "${files[@]}"; then
    echo "Some files still use $OLD. The originals are in $backup." >&2
    exit 1
fi
echo "Switched to $NEW. The originals are in $backup."

if [ "$restart" -eq 0 ]; then
    echo "Restart the Squirro services to apply the change."
    finish
fi
mapfile -t units < <(systemctl list-unit-files 'sq*d.service' --state=enabled --no-legend | awk '{print $1}')
echo "Restarting ${#units[@]} Squirro services..."
systemctl restart "${units[@]}" || true
# A service that keeps crashing shows as running most of the time, so count its restarts.
declare -A restarts
for unit in "${units[@]}"; do
    restarts[$unit]=$(systemctl show -p NRestarts --value "$unit")
done
sleep 30
failing=()
for unit in "${units[@]}"; do
    if ! systemctl is-active --quiet "$unit" \
        || [ "$(systemctl show -p NRestarts --value "$unit")" != "${restarts[$unit]}" ]; then
        failing+=("$unit")
    fi
done
if [ ${#failing[@]} -gt 0 ]; then
    echo "Stopped or restarting 30 seconds after the restart, see their logs in /var/log/squirro:" >&2
    printf '  %s\n' "${failing[@]}" >&2
    exit 1
fi
echo "All Squirro services are running."
finish
