#!/bin/bash
set -e

ROOT_PREFIX=${URBM_ROOT_PREFIX:-}
CONFIG="$ROOT_PREFIX/boot/config/plugins/urbm"
OLD_NAME="back""upper"
OLD_CONFIG="$ROOT_PREFIX/boot/config/plugins/$OLD_NAME"

if [ -x "$ROOT_PREFIX/etc/rc.d/rc.$OLD_NAME" ]; then
  "$ROOT_PREFIX/etc/rc.d/rc.$OLD_NAME" stop || true
fi

mkdir -p "$CONFIG" "$ROOT_PREFIX/run/urbm" "$ROOT_PREFIX/var/lib/urbm"
if [ -d "$OLD_CONFIG" ]; then
  for item in config.json runs.json secrets; do
    if [ -e "$OLD_CONFIG/$item" ] && [ ! -e "$CONFIG/$item" ]; then
      cp -a "$OLD_CONFIG/$item" "$CONFIG/$item"
    fi
  done
fi

if [ -f "$CONFIG/config.json" ]; then
  sed \
    -e "s#/usr/local/libexec/$OLD_NAME/restic#/usr/local/libexec/urbm/restic#g" \
    -e "s#/mnt/user/$OLD_NAME-restores#/mnt/user/urbm-restores#g" \
    -e "s#/mnt/user/system/$OLD_NAME-logs#/mnt/user/system/urbm-logs#g" \
    "$CONFIG/config.json" > "$CONFIG/config.json.migrated"
  chmod 0600 "$CONFIG/config.json.migrated"
  mv "$CONFIG/config.json.migrated" "$CONFIG/config.json"
fi

chmod 0700 "$CONFIG"
chmod 0750 "$ROOT_PREFIX/run/urbm" "$ROOT_PREFIX/var/lib/urbm"

rm -rf \
  "$ROOT_PREFIX/usr/local/emhttp/plugins/$OLD_NAME" \
  "$ROOT_PREFIX/usr/local/libexec/$OLD_NAME" \
  "$ROOT_PREFIX/usr/local/sbin/${OLD_NAME}d" \
  "$ROOT_PREFIX/etc/rc.d/rc.$OLD_NAME" \
  "$ROOT_PREFIX/run/$OLD_NAME" \
  "$ROOT_PREFIX/var/lib/$OLD_NAME" \
  "$OLD_CONFIG"
rm -f \
  "$ROOT_PREFIX/boot/config/plugins/$OLD_NAME.plg" \
  "$ROOT_PREFIX/var/log/plugins/$OLD_NAME.plg" \
  "$ROOT_PREFIX/tmp/plugins/$OLD_NAME.plg" \
  "$ROOT_PREFIX/tmp/plugins/$OLD_NAME.txt" \
  "$ROOT_PREFIX/var/log/$OLD_NAME.log"

if [ -x "$ROOT_PREFIX/etc/rc.d/rc.urbm" ]; then
  "$ROOT_PREFIX/etc/rc.d/rc.urbm" restart || true
fi
