asterisk_stop() {
    local pid
    local astcanary_pid
    local rc

    asterisk_status
    rc=$?
    if [ $rc -eq $OCF_NOT_RUNNING ]; then
        ocf_log info "Asterisk PBX already stopped"
        return $OCF_SUCCESS
    fi

    # do a "soft shutdown" via the asterisk command line first
    asterisk_rx 'core stop now'

    asterisk_status
    rc=$?
    if [ $rc -eq $OCF_NOT_RUNNING ]; then
        ocf_log info "Asterisk PBX stopped"
        return $OCF_SUCCESS
    fi

    # If "core stop now" didn't succeed, try SIGTERM
    pid=`cat $ASTRUNDIR/asterisk.pid`
    ocf_run kill -s TERM $pid
    rc=$?
    if [ $rc -ne 0 ]; then
        ocf_log err "Asterisk PBX couldn't be stopped"
        exit $OCF_ERR_GENERIC
    fi

    # stop waiting
    shutdown_timeout=15
    if [ -n "$OCF_RESKEY_CRM_meta_timeout" ]; then
        shutdown_timeout=$((($OCF_RESKEY_CRM_meta_timeout/1000)-5))
    fi
    count=0
    while [ $count -lt $shutdown_timeout ]; do
        asterisk_status
        rc=$?
        if [ $rc -eq $OCF_NOT_RUNNING ]; then
            break
        fi
        count=`expr $count + 1`
        sleep 1
        ocf_log debug "Asterisk PBX still hasn't stopped yet. Waiting ..."
    done

    asterisk_status
    rc=$?
    if [ $rc -ne $OCF_NOT_RUNNING ]; then
        # SIGTERM didn't help either, try SIGKILL
        ocf_log info "Asterisk PBX failed to stop after ${shutdown_timeout}s using SIGTERM. Trying SIGKILL ..."
        ocf_run kill -s KILL $pid
    fi

    # After killing asterisk, stop astcanary
    if ocf_is_true "$OCF_RESKEY_realtime"; then
      astcanary_pid=`pgrep -d " " -f "astcanary $ASTRUNDIR/alt.asterisk.canary.tweet.tweet.tweet"`
      if [ "$astcanary_pid" ]; then
        for i in $astcanary_pid; do ocf_run kill -s KILL $astcanary_pid; done
      fi
    fi

    ocf_log info "Asterisk PBX stopped"
    return $OCF_SUCCESS
}
