#!/bin/sh

# SPDX-FileCopyrightText: (C) 2025 NetKnights GmbH <https://netknights.it>
# SPDX-License-Identifier: AGPL-3.0-or-later

set -e

MIGRATION_DIR=""

usage()
{
  echo "Usage: $0 [OPTIONS]"
  echo ""
  echo "OPTIONS:"
  echo "    -h, --help           Show this help text"
  echo "    -d, --migration_dir  The path to the directory with the scripts for the database migration"
  echo "    -s, --skipstamp      Ignored, the database is never stamped by this script"
  exit "$1"
}

while [ "$#" -gt 0 ]; do
  case $1 in
    -d|--migration_dir)
      if [ "$#" -lt 2 ] || [ -z "$2" ]; then
        echo "Option $1 requires a directory"
        usage 1
      fi
      MIGRATION_DIR="$2"
      shift # past argument
      shift # past value
      ;;
    -s|--skipstamp)
      shift # past argument
      ;;
    -h|--help)
      usage 0
      ;;
    -*|--*)
      echo "Unknown option $1"
      usage 1
      ;;
    *)
      echo "Unknown argument $1"
      usage 1
      ;;
  esac
done

# The arguments for pi-manage are kept in the positional parameters, so that a path with spaces stays one argument.
if [ "${MIGRATION_DIR}" ]; then
  if [ ! -d "${MIGRATION_DIR}" ]; then
    echo "ERROR: The migration directory '${MIGRATION_DIR}' does not exist."
    exit 1
  fi
  echo "Using path '${MIGRATION_DIR}' for the migration."
  set -- -d "${MIGRATION_DIR}"
fi

# "pi-manage db current -v" prints "Current revision(s) for <database URL without password>:" and one line
# "Rev: <revision> (head)" per revision the database is stamped with. The revisions are printed on one line, "none"
# for a database without stamp.
revisions()
{
  revision_list=$(printf '%s\n' "$1" | sed -n 's/^Rev: //p' | paste -s -d ' ' -)
  echo "${revision_list:-none}"
}

if ! current_output=$(pi-manage db current -v "$@"); then
  printf '%s\n' "${current_output}"
  echo "ERROR: The schema revision of the database could not be read."
  exit 1
fi
database=$(printf '%s\n' "${current_output}" | sed -n 's/^Current revision(s) for \(.*\):$/\1/p')
echo "++ Database: ${database}"
echo "++ Schema revision before the upgrade: $(revisions "${current_output}")"

# "pi-manage db upgrade" stops on a database without schema revision stamp and says what to do.
echo "++ Upgrading DB schema."
upgrade_status=0
pi-manage db upgrade "$@" || upgrade_status=$?

if current_output=$(pi-manage db current -v "$@"); then
  echo "++ Schema revision after the upgrade: $(revisions "${current_output}")"
else
  printf '%s\n' "${current_output}"
  echo "ERROR: The schema revision of the database could not be read after the upgrade."
fi
exit "${upgrade_status}"
