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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "${SCRIPT_DIR}/remote-common.sh"

INSTALL_DEPS="${INSTALL_DEPS:-0}"
BUILD_SHARED="${BUILD_SHARED:-0}"
BUILD_API="${BUILD_API:-0}"
BUILD_WEB="${BUILD_WEB:-0}"
RUN_MIGRATIONS="${RUN_MIGRATIONS:-0}"
RESTART_API="${RESTART_API:-0}"
RESTART_WEB="${RESTART_WEB:-0}"
DAEMON_RELOAD="${DAEMON_RELOAD:-0}"

WEB_STATIC_CACHE_DIR=".deploy-cache/previous-next-static"

preserve_previous_web_assets_before_build() {
  run_in_root /bin/rm -rf "${WEB_STATIC_CACHE_DIR}"

  if run_in_root test -d apps/web/.next/static; then
    run_in_root /bin/mkdir -p "${WEB_STATIC_CACHE_DIR}"
    run_in_root /usr/bin/rsync -a apps/web/.next/static/ "${WEB_STATIC_CACHE_DIR}/"
  fi
}

restore_previous_web_assets_after_build() {
  if ! run_in_root test -d "${WEB_STATIC_CACHE_DIR}"; then
    return
  fi

  run_in_root /bin/mkdir -p apps/web/.next/static
  run_in_root /usr/bin/rsync -a --ignore-existing "${WEB_STATIC_CACHE_DIR}/" apps/web/.next/static/
  run_in_root /bin/rm -rf "${WEB_STATIC_CACHE_DIR}"
}

run_in_root true

if [[ "${INSTALL_DEPS}" == "1" ]]; then
  run_in_root /usr/bin/npm install
fi

if [[ "${BUILD_SHARED}" == "1" ]]; then
  run_in_root /usr/bin/npm run build --workspace @rental/shared
fi

if [[ "${BUILD_API}" == "1" ]]; then
  run_in_root /usr/bin/npm run build --workspace @rental/api
fi

if [[ "${BUILD_WEB}" == "1" ]]; then
  preserve_previous_web_assets_before_build
  run_in_root /usr/bin/npm run build --workspace @rental/web
  restore_previous_web_assets_after_build
fi

if [[ "${RUN_MIGRATIONS}" == "1" ]]; then
  run_in_root /usr/bin/npm run db:migrate --workspace @rental/api
fi

if [[ "${DAEMON_RELOAD}" == "1" ]]; then
  daemon_reload
fi

if [[ "${RESTART_API}" == "1" ]]; then
  restart_unit rental-api.service
fi

if [[ "${RESTART_WEB}" == "1" ]]; then
  restart_unit rental-web.service
fi
