#!/usr/bin/bash
#
# Restore 3rd party IDS stopped by disable_3rd_party_ids
#

STATE=/var/imunify360/.disabled_3rd_party_ids

is_systemctl_avail() {
    which systemctl >/dev/null 2>&1
}

restore_service() {
    local servicename=$1 state=$2
    case "$servicename" in
    cphulk)
        whmapi1 enable_cphulk
        ;;
    *)
        if is_systemctl_avail
        then
            local rc=0
            if [ "$state" = enabled ]
            then
                systemctl enable "$servicename" || rc=1
            fi
            # started even if it could not be enabled: protected until reboot
            systemctl start "$servicename" || rc=1
            return $rc
        else
            chkconfig --add "$servicename" && service "$servicename" start
        fi
        ;;
    esac
}

hint() {
    local servicename=$1 state=$2
    case "$servicename" in
    cphulk) echo "whmapi1 enable_cphulk" ;;
    *)
        if [ "$state" = enabled ]
        then
            echo "systemctl enable --now $servicename"
        else
            echo "systemctl start $servicename"
        fi
        ;;
    esac
}

if [ ! -f "$STATE" ]
then
    # installed before the record was kept: nothing says what was disabled
    if is_systemctl_avail \
        && [ "$(systemctl is-enabled fail2ban 2>/dev/null)" = disabled ]
    then
        echo "fail2ban is installed but disabled. If Imunify360 disabled it," \
            "re-enable it: $(hint fail2ban enabled)"
    fi
    if [ -x /usr/local/cpanel/cpanel ]
    then
        echo "If Imunify360 disabled cPHulk, re-enable it: $(hint cphulk enabled)"
    fi
    exit 0
fi

while read -r servicename state
do
    [[ "$servicename" =~ ^[A-Za-z0-9][A-Za-z0-9_.@-]*$ ]] || continue
    echo "-- Restoring $servicename disabled by Imunify360"
    if ! restore_service "$servicename" "$state" </dev/null >/dev/null
    then
        echo "-- Could not restore $servicename, run: $(hint "$servicename" "$state")"
    fi
done < "$STATE"
rm -f "$STATE"
exit 0
