#!/bin/bash

set -euEo pipefail

if [[ $# -lt 2 ]]; then
  echo "ERROR: not enough parameters!" >&2
  echo "Should be '$0' '<File to change>' '<number of symbols>'" >&2
  exit 1
fi

file="$1"
num_of_symbols="$2"

# shellcheck disable=SC2016
sed -i --follow-symlinks 's/\(.*\)PW_OPENSSL_\([0-9]\+\)_\(hex\|base64\)\(.*\)/echo "\1$(openssl rand -\3 \2)\4"/e' "${file}"

sed -i --follow-symlinks "s/PW_MYSQL/$(openssl rand -hex 32)/" "${file}"

while grep -q -E 'PW_[^[:space:]]+' "${file}"; do
  NEW_PW=$(pwgen -c -0 -s -B "${num_of_symbols}" 1)
  sed -i --follow-symlinks -r "0,/PW_[^[:space:]]+/s//${NEW_PW}/" "${file}"
done
