#!/bin/bash

error() {
    echo -e "\n\033[31m** ERROR: $1\033[0m\n" && exit 1
}

checkRoot() {
    curUser=
    if [ -x "/usr/xpg4/bin/id" ]
    then
        curUser=$(/usr/xpg4/bin/id -nu)
    else
        curUser=$(id -nu)
    fi
    if [ "$curUser" != "root" ]
    then
        error "Only root user can install artifactory as a service"
    fi

    if [ "$0" = "." ] || [ "$0" = "source" ]; then
        error "Cannot execute script with source $0"
    fi
}

shutdownService() {
    if [ -f ${artServiceFile} ]; then
        SERVICE_STATUS="$(${artServiceFile} status)"
        if [[ ! "$SERVICE_STATUS" =~ .*[sS]topped.* ]]; then
            echo
            echo -n "Stopping the artifactory service..."
            ${artServiceFile} stop || exit $?
            echo -e " DONE"
        fi
    fi
    if [ -f ${artSystemdFile} ]; then
        SERVICE_STATUS="$(systemctl status artifactory.service)"
        if [[ ! "$SERVICE_STATUS" =~ .*[sS]topped.* ]]; then
            echo
            echo -n "Stopping the artifactory service..."
            systemctl stop artifactory.service || exit $?
            echo -e " DONE"
        fi
    fi
}

uninstallInitdService() {
  if [ -x /usr/sbin/update-rc.d ]; then
    /usr/sbin/update-rc.d -f ${serviceInitName} remove &>/dev/null && removeOk=true
  elif [ -x /usr/sbin/chkconfig ]; then
    /usr/sbin/chkconfig --del ${serviceInitName} &>/dev/null && removeOk=true
  elif [ -x /sbin/chkconfig ]; then
    /sbin/chkconfig --del ${serviceInitName} &>/dev/null && removeOk=true
  fi

  [ ${removeOk} ] || error "Could not uninstall service"

  removeOk=
  if [ -x ${artServiceFile} ]; then
    rm -f ${artServiceFile} && removeOk=true
    rm -f ${artServiceFile}.disable &>/dev/null
  fi

  [ ${removeOk} ] || error "Could not delete $artServiceFile"

  removeOk=
  rm ${TOMCAT_HOME}/bin/setenv.sh && removeOk=true

  [ ${removeOk} ] || error "Could not delete $TOMCAT_HOME/bin/setenv.sh"
  echo -e " DONE"
}

uninstallSystemdService() {
  systemctl disable ${serviceSystemdName} &>/dev/null || error "Could not uninstall service"

  if [ -f ${artSystemdFile} ]; then
    rm -f ${artSystemdFile} || error "Could not delete $artSystemdFile"
  fi

  if [ -f ${artSystemdLibFile} ]; then
    rm -f ${artSystemdLibFile} || error "Could not delete $artSystemdLibFile"
  fi

  rm -f ${TOMCAT_HOME}/bin/setenv.sh || error "Could not delete $TOMCAT_HOME/bin/setenv.sh"
  echo -e " DONE"
}

uninstallService() {
    echo -n "Removing the artifactory service from auto-start..."
    # Check if init.d service was installed
    if [ -f ${artServiceFile} ]; then
        uninstallInitdService
    fi
    # Check if systemd service was installed
    if [ -f ${artSystemdFile} ]; then
        uninstallSystemdService
    fi
}

moveDir() {
  local src=$1
  local dest=$2

  if [ -z "${src}" ] || [ -z "${dest}" ]; then
    return
  fi

  if [ -d "$src" ]; then
    echo "Moving directory ${src} to ${dest}"
    mv "${src}" "${dest}" || exit $?
  fi
}

createBackup() {
  # if some files in data move them to a backup folder
  if [ -d "${JF_PRODUCT_HOME}/var/etc" ] || [ -d "${JF_PRODUCT_HOME}/var/data" ] || [ -d "${JF_PRODUCT_HOME}/var/log" ]; then
    TIMESTAMP=$(echo "$(date '+%T')" | tr -d ":")
    CURRENT_TIME="$(date '+%Y%m%d').$TIMESTAMP"
    BACKUP_DIR="${JF_PRODUCT_HOME}/artifactory.backup.${CURRENT_TIME}"

    echo "Creating a backup of the artifactory home folder in ${BACKUP_DIR}..."
    mkdir -p "${BACKUP_DIR}" || exit $?
    moveDir "${productEtcDir}" "${BACKUP_DIR}/etc"
    moveDir "${JF_PRODUCT_HOME}/var/data" "${BACKUP_DIR}/data"
    moveDir "${JF_PRODUCT_HOME}/var/log" "${BACKUP_DIR}/log"

    rm -rf "${JF_PRODUCT_HOME}/var/backup"
    rm -rf "${JF_PRODUCT_HOME}/var/bootstrap"
    rm -rf "${JF_PRODUCT_HOME}/var/work"

    if [ -e ${TOMCAT_HOME}/lib/mysql-connector-java*.jar ]; then
      echo; echo -n "MySQL connector found"
      mv ${TOMCAT_HOME}/lib/mysql-connector-java* "${BACKUP_DIR}" || exit $?
    fi
  fi
}

removeArtUser() {
  echo "Logging off user $JF_ARTIFACTORY_USER..."
  pkill -KILL -u ${JF_ARTIFACTORY_USER}

  rm -rf ${JF_PRODUCT_HOME}/app/tomcat/work/* || exit $?

  # Ignoring user folders since the home dir is deleted already by the RPM spec
  echo; echo -n "Removing user $JF_ARTIFACTORY_USER..."
  userdel ${JF_ARTIFACTORY_USER} || exit $?

  EXISTING_GROUP="$(grep $artGroup /etc/group | awk -F ':' '{ print $1 }' 2>/dev/null)"
  if [ "$EXISTING_GROUP" == "$artGroup" ]; then
    echo -n "Removing group $artGroup"
    groupdel ${artGroup}
  fi
  echo -e " DONE"
}

removeResources() {
  rm -rf ${productEtcDir} && \
  removeOk=true

  [ ${removeOk} ] || error "Could not remove ${productEtcDir} directory"

  rm -rf ${TOMCAT_HOME}/logs
  if [ -d ${TOMCAT_HOME}/logs.original ]; then
    mv ${TOMCAT_HOME}/logs.original ${TOMCAT_HOME}/logs
  fi
}

showSummary() {
    echo
    echo -e "\033[33mUninstallation of Artifactory completed\033[0m"
    echo -e "Please change the permissions of ${JF_PRODUCT_HOME}/app"
}

sourceScript(){
    local fileName=$1

    [ ! -z "${fileName}" ] || errorExit "Target file is not set"
    [   -f "${fileName}" ] || errorExit "${fileName} file is not found"
    source "${fileName}"   || errorExit "Unable to source ${fileName}, please check if the $USER user has permissions to perform this action"
}

initHelpers(){
    local systemYamlHelper="${ARTIFACTORY_BIN_FOLDER}"/systemYamlHelper.sh
    local installerCommon="${ARTIFACTORY_BIN_FOLDER}"/installerCommon.sh
    local artCommon="${ARTIFACTORY_BIN_FOLDER}"/artifactoryCommon.sh

    export YQ_PATH="${ARTIFACTORY_BIN_FOLDER}/../third-party/yq"

    sourceScript "${systemYamlHelper}"
    sourceScript "${installerCommon}"
    sourceScript "${artCommon}"

    # init at each service startup 
    export JF_SYSTEM_YAML="${JF_PRODUCT_HOME}/var/etc/system.yaml"
}


ARTIFACTORY_BIN_FOLDER="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
artExtractDir="$(cd "$(dirname "$ARTIFACTORY_BIN_FOLDER")" && pwd)"

[ -n "${JF_PRODUCT_HOME}" ] || JF_PRODUCT_HOME="$(cd "$(dirname "$ARTIFACTORY_BIN_FOLDER")"/.. && pwd)"
[ -n "$productEtcDir" ] || productEtcDir="${JF_PRODUCT_HOME}/var/etc"
[ -n "$artServiceFile" ] || artServiceFile="/etc/init.d/artifactory"
[ -n "$artSystemdFile" ] || artSystemdFile="/etc/systemd/system/artifactory.service"
serviceInitName=$(basename ${artServiceFile})
serviceSystemdName=$(basename ${artSystemdFile})
artSystemdLibFile="/lib/systemd/system/artifactory.service"
artDefaultFile="${ARTIFACTORY_BIN_FOLDER}/artifactory.default"

checkRoot

. ${artDefaultFile} || error "$artDefaultFile does not exist or not executable"

initHelpers

# This will set JF_ARTIFACTORY_USER and JF_ARTIFACTORY_GROUP (default artifactory:artifactory)
setUserGroup "$1" "$2"

artGroup="$JF_ARTIFACTORY_USER"

shutdownService

uninstallService

createBackup

removeArtUser

removeResources

showSummary
