APP_NAME="beer-garden"
GROUP=$APP_NAME
USER=$APP_NAME
APP_HOME="/opt/${APP_NAME}"

CONFIG_HOME="$APP_HOME/conf"
PLUGIN_HOME="$APP_HOME/plugins"
CHILDREN_CONFIG_HOME="$CONFIG_HOME/children"
CONFIG_FILE="${CONFIG_HOME}/config.yaml"
APP_LOG_CONFIG="${CONFIG_HOME}/app-logging.yaml"
LOCAL_PLUGIN_LOG_CONFIG="${CONFIG_HOME}/local-plugin-logging.yaml"
REMOTE_PLUGIN_LOG_CONFIG="${CONFIG_HOME}/remote-plugin-logging.yaml"
JOB_STARTUP_FILE="${CONFIG_HOME}/scheduled_jobs.json"

LOG_HOME="$APP_HOME/log"
PLUGIN_LOG_HOME="$LOG_HOME/plugins"
APP_LOG_FILE="$LOG_HOME/beer-garden.log"
PLUGIN_LOG_FILE="${PLUGIN_LOG_HOME}/%%(namespace)s/%%(system_name)s-%%(system_version)s/%%(instance_name)s.log"

BEERCTL="/usr/bin/beerctl"

case "$1" in
    0)
        # This is an uninstallation
        # Remove the user
        /usr/sbin/userdel $APP_NAME

        # Remove the UI config file symlinks
        if [ -L "/etc/nginx/conf.d/upstream.conf" ]; then
            unlink "/etc/nginx/conf.d/upstream.conf"
        fi
        if [ -L "/etc/nginx/default.d/bg.conf" ]; then
            unlink "/etc/nginx/default.d/bg.conf"
        fi
    ;;
    1)
        # This is an upgrade.
        # Migrate application config if it exists
        # See https://github.com/beer-garden/beer-garden/issues/215
        if [ -f "$CONFIG_FILE" ]; then
            "$APP_HOME/bin/migrate_config" \
            -c "$CONFIG_FILE" -l "$APP_LOG_CONFIG" \
            --plugin-local-directory "$PLUGIN_HOME" \
            --plugin-local-logging-config-file "$LOCAL_PLUGIN_LOG_CONFIG" \
            --plugin-remote-logging-config-file "$REMOTE_PLUGIN_LOG_CONFIG" \
            --children-directory "$CHILDREN_CONFIG_HOME" \
            --scheduler-job-startup-file "$JOB_STARTUP_FILE"

            # Set owner and group of new config
            chown ${USER}:${GROUP} $CONFIG_FILE
        fi
    ;;
esac

# Remove beerctl
if [ -f "$BEERCTL" ]; then
    rm "$BEERCTL"
fi

# Reload units
systemctl daemon-reload
