#!/usr/bin/env bash
set -euo pipefail

APP_DATA_DIR="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../data)"
ORDINALS_DATA_DIR="${APP_DATA_DIR}/ord"
DESIRED_OWNER="1000:1000"

set_correct_permissions() {
	local -r path="${1}"

	if [[ -d "${path}" ]]; then
		owner=$(stat -c "%u:%g" "${path}")

		if [[ "${owner}" != "${DESIRED_OWNER}" ]]; then
			chown -R "${DESIRED_OWNER}" "${path}"
		fi
	fi
}

# handle generating the correct ord data dir for pre-0.15.0 versions
if [[ -f "${APP_DATA_DIR}/index.redb" ]]; then
  rm -f "${APP_DATA_DIR}/index.redb"
  mkdir -p "${ORDINALS_DATA_DIR}"
  # set correct permissions for both data and ord
  set_correct_permissions "${APP_DATA_DIR}"
fi

# re-index the ordinals data for runes
# for installs post 0.18.1 this file will be harmlessly created 
if [[ ! -f "${APP_DATA_DIR}/AT_LEAST_0-18-1" ]]; then
    # delete index db for all bitcoin networks
    for file in "${ORDINALS_DATA_DIR}/index.redb" "${ORDINALS_DATA_DIR}/testnet3/index.redb" "${ORDINALS_DATA_DIR}/regtest/index.redb" "${ORDINALS_DATA_DIR}/signet/index.redb"; do
        if [[ -f "${file}" ]]; then
            rm -f "${file}"
        fi
    done
    touch "${APP_DATA_DIR}/AT_LEAST_0-18-1"
fi





