#!/bin/bash

save_cwd=`pwd`
SERVER_ROOT="/Applications/Server.app/Contents/ServerRoot"
DEVICEMGR_PATH="$SERVER_ROOT/usr/share/devicemgr"

source $DEVICEMGR_PATH/config/common.sh       # Loads all our path definitions and some other common variables

STOPPED=`$SERVERADMIN status devicemgr | grep "STOPPED"`

if [ -z "$STOPPED" ]; then
  $SERVERADMIN stop devicemgr
fi

# Stop our "always on" devicemgrd so we can drop the DB
$SERVERCTL disable service=com.apple.DeviceManagement.devicemgrd

# Have to manually start PostgreSQL on our cluster
$SERVERCTL enable service=com.apple.DeviceManagement.postgres

# Load scep_helper before migration because we might need it to sign profile caches that we re-generate during migration
$SERVERCTL enable service=com.apple.DeviceManagement.SCEPHelper

sudo /bin/rm -f /Library/Server/ProfileManager/Config/ServiceData/Data/models 

# migration_tool will drop and re-create the database
sudo -u _devicemgr $MIGRATION_PATH/migration_tool "$@"
if [ $? -ne 0 ]; then
  echo "**************************************************************************"
  echo "***    Failed to create/update new Profile Manager database!           ***"
  echo "**************************************************************************"
  echo "*** Please check $PM_MIGRATION_LOG_FILE       ***"
  echo "*** for more information. Profile Manager will be non-functional until ***"
  echo "*** the database can be successfully updated or a new one is created.  ***"
  echo "**************************************************************************"
  exit 1
fi

# The above might cause PM_RAILS_LOG_FILE to be owned by root, so fix that
if [ -f $PM_RAILS_LOG_FILE ]; then
  chown $PM_USERNAME:admin $PM_RAILS_LOG_FILE
fi

$SERVERCTL enable service=com.apple.DeviceManagement.devicemgrd

if [ -z "$STOPPED" ]; then
  $SERVERADMIN start devicemgr
  cd $BACKEND_LIB_PATH
  sudo ./dm_tool -a noOp    # Get devicemgrd running
fi

cd "$save_cwd"
