#!/system/bin/sh
#
# look for users that are missing the password_hex key, and generate
# it from password_cleartext if needed.

CFG_FILE="/drd-data/config/installation/config.json"
TMPDIR="/data/local/tmp"

mkdir -p "${TMPDIR}"

function update_json() {
	prefix=$1
	shift
	fname=$1
	shift
	query=$@
	shift
	if [ "${prefix}"x = ""x ] ; then
		echo "missing prefix"
		return 10
	fi
	if [ "${fname}"x = ""x ] ; then
		echo "missing fname"
		return 11
	fi
	if [ "${query}"x = ""x ] ; then
		echo "missing query"
		return 12
	fi
	if [ ! -f "${fname}" ] ; then
		echo "file ${fname} does not exist"
		return 13
	fi
	tmp_file="$(mktemp -p ${TMPDIR})"
	if [ $? -ne 0 ] ; then
		echo "unable to create tempfile"
		return 14
	fi
	jq -c -e "${query}" "${fname}" > "${tmp_file}"
	if [ $? -ne 0 ] ; then
		echo "wrong query" 15
		return
	fi
	cp "${tmp_file}" "${fname}"
	sync
  return 0
}

if [ ! -f "${CFG_FILE}" ] ; then
  echo "missing ${CFG_FILE} file"
  exit 0
fi

tmpfile="$(mktemp -p ${TMPDIR})"
if [ $? -ne 0 ] ; then
  echo "unable to create tempfile"
  exit 1
fi

cp "${CFG_FILE}" "${tmpfile}"
if [ $? -ne 0 ] ; then
  echo "unable to copy ${CFG_FILE} to ${tmpfile}"
  exit 1
fi

# another possible query that doesn't rely on .username is: '.mqtt_devices | with_entries(select(.password_hex == "" or .password_hex == null) | keys'
TO_MIGRATE="$(cat "${tmpfile}" | jq -r '.mqtt_devices[] | select(.password_hex == "" or .password_hex == null) | .username')"
ret=$?
if [ $ret -ne 0 ] ; then
  echo "failed to fetch .installation.mqtt_devices"
  exit $ret
fi

if [ -z "${TO_MIGRATE}" ] ; then
  echo "no users to migrate"
  exit 0
fi

was_run=0
for username in ${TO_MIGRATE}
do
  cleartext="$(cat "${tmpfile}" | jq -r '.mqtt_devices["'${username}'"]'.password_cleartext)"
  ret=$?
  if [ $ret -ne 0 ] ; then
    echo "unable to fetch password_cleartext for user ${password_cleartext}"
    continue
  fi
  if [ -z "${cleartext}" ] ; then
    echo "empty password_cleartext for user ${password_cleartext}"
    continue
  fi
  hex="$(echo -n "${cleartext}" | xxd -p | tr -d '\n' | tr  -d ' ')"
  ret=$?
  if [ $ret -ne 0 ] ; then
    echo "failed to transform cleartext ${password_cleartext} to hex"
    continue
  fi
  if [ -z "${hex}" ] ; then
    echo "empty password_hex for user ${password_cleartext}"
    continue
  fi
  update_json "migrate_hexpasswords" "${tmpfile}" ".mqtt_devices[\"${username}\"].password_hex=\"${hex}\""
  ret=$?
  if [ $ret -ne 0 ] ; then
    echo "failed to set password_hex to ${hex} for user ${username}"
    continue
  fi
  was_run=1
done

if [ $was_run -eq 1 ] ; then
  cat "${tmpfile}" | jq -e -c . &> /dev/null
  if [ $? -ne 0 ] ; then
    echo "invalid json"
    exit 1
  fi
  cp "${tmpfile}" "${CFG_FILE}"
  # in case ConfigServer was up, run triggers
  curl -s "http://127.0.0.1:4321/?runtriggers=true" &> /dev/null
fi

rm -f "${tmpfile}"
exit 0