#!/bin/bash
# Description   :   This script is used to migrate mac agent from EC to EC/PMP/RAP/other point products 
#
# Returns       :   0 if executed successfully.
#                   1 if agent Migration failed.
#
# Maintainer    :   ManageEngine Desktop Central <desktopcentral-support@manageengine.com>

verifyAndCopyFiles() {
    # verify and copy dependency files
    dependency=( "UEMS_MacAgent.pkg" "serverinfo.plist")

    for item in "${dependency[@]}"
    do
        if [[ -f "$item" ]]; then
            echo "$item exist."
        else
            echo "$item missing."
            exit 1
        fi
        
        cp $item /tmp
        errcode=$?
        if [ "$errcode" -ne 0 ]; then
            echo "Failed to copy $item with errorcode $errcode"
            exit 1
        fi
    done

    # optional files. ignore verification
    cp DMRootCA-Server.crt /tmp
    cp DMRootCA.crt /tmp
}

uninstallAgent() {
    # Uninstall agent
    if [ -d "/Library/DesktopCentral_Agent/Uninstaller.app" ]; then
        echo "DC Uninstaller.app exist"
        /Library/DesktopCentral_Agent/Uninstaller.app/Contents/MacOS/Uninstaller -silent
    elif [ -d "/Library/UEMS_Agent/Uninstaller.app" ]; then
        echo "UEMS Uninstaller.app exist"
        /Library/UEMS_Agent/Uninstaller.app/Contents/MacOS/Uninstaller -silent
    elif [ -d "/Library/ManageEngine/UEMS_Agent/Uninstaller.app" ]; then
         echo "UEMS Uninstaller.app exist"
        /Library/ManageEngine/UEMS_Agent/Uninstaller.app/Contents/MacOS/Uninstaller -silent
    fi
    errcode=$?
    if [ "$errcode" -ne 0 ]; then
        echo "Failed to uninstall Agent with errorcode $errcode"
        exit 1
    fi

    sleep 3
}

checkandInstallAgent() {
    PROCESS=dcconfig
    number=$(ps aux | grep -v grep | grep -ci $PROCESS)
    while [ $number -gt 0  ]
    do
        echo "dcconfig running... wait for it to end"
        number=$(ps aux | grep -v grep | grep -ci $PROCESS)
    done
    
    # Install agent
    cd /tmp
    /usr/sbin/installer -pkg UEMS_MacAgent.pkg -target /
}

verifyAndCopyFiles
uninstallAgent
checkandInstallAgent >/private/tmp/out 2>&1 &

exit 0


