asterisk_start() {
    local asterisk_extra_params
    local dir
    local rc

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

    # If Asterisk is not already running, make sure there is no
    # old astcanary instance when the new asterisk starts. To
    # achieve this, kill old astcanary instances belonging to
    # this $ASTRUNDIR.

    # Find out PIDs of running astcanaries
    astcanary_pid=`pgrep -d " " -f "astcanary $ASTRUNDIR/alt.asterisk.canary.tweet.tweet.tweet"`

    # If there are astcanaries running that belong to $ASTRUNDIR,
    # kill them.
    if [ "$astcanary_pid" ]; then
      for i in $astcanary_pid; do ocf_run kill -s KILL $astcanary_pid; done
    fi

    for dir in $ASTRUNDIR $ASTLOGDIR $ASTLOGDIR/cdr-csv $ASTLOGDIR/cdr-custom; do
        if [ ! -d "$dir" ]; then
            ocf_run install -d -o $OCF_RESKEY_user -g $OCF_RESKEY_group $dir \
                || exit $OCF_ERR_GENERIC
        fi
        # Regardless of whether we just created the directory or it
        # already existed, check whether it is writable by the configured
        # user
        if ! su -s /bin/sh - $OCF_RESKEY_user -c "test -w $dir"; then
            ocf_log err "Directory $dir is not writable by $OCF_RESKEY_user"
            exit $OCF_ERR_PERM
        fi
    done

    # set MAXFILES
    ulimit -n $OCF_RESKEY_maxfiles

    # Determine whether Asterisk PBX is supposed to run in Realtime mode
    # or not and make asterisk daemonize automatically
    if ocf_is_true "$OCF_RESKEY_realtime"; then
      asterisk_extra_params="-F -p"
    else
      asterisk_extra_params="-F"
    fi

    ocf_run ${OCF_RESKEY_binary} -G $OCF_RESKEY_group -U $OCF_RESKEY_user \
                -C $OCF_RESKEY_config \
                $OCF_RESKEY_additional_parameters \
                $asterisk_extra_params
    rc=$?
    if [ $rc -ne 0 ]; then
        ocf_log err "Asterisk PBX start command failed: $rc"
        exit $OCF_ERR_GENERIC
    fi

    # Spin waiting for the server to come up.
    # Let the CRM/LRM time us out if required
    while true; do
        asterisk_monitor
        rc=$?
        [ $rc -eq $OCF_SUCCESS ] && break
        if [ $rc -ne $OCF_NOT_RUNNING ]; then
            ocf_log err "Asterisk PBX start failed"
            exit $OCF_ERR_GENERIC
        fi
        sleep 2
    done

    ocf_log info "Asterisk PBX started"
    return $OCF_SUCCESS
}
