/*
 * Copyright (c) 2001-2003 Shiman Associates Inc. All Rights Reserved.
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

#include <string.h>
#include <mas_internal.h>
#include "procstat.h"

static int   _procstat_active = FALSE;
static char* _procstat_argv0 = NULL;
static int   _procstat_argv0_len = 0;
static char  _procstat_prefix[] = "mas ";
static int   _procstat_prefix_len = 0;

int32
procstat_init( char* argv0, int active )
{
    _procstat_argv0_len = strlen( argv0 );
    _procstat_prefix_len = strlen( _procstat_prefix );

    /* Just to be sure, this is an opt-in feature.  "linux" is a
     * preprocessor define. */
#ifndef linux
    _procstat_active = FALSE;
    return mas_error(MERR_INVALID);
#endif /* linux */
    

    if ( _procstat_argv0_len <= strlen( "mas active" ) )
    {
        _procstat_active = FALSE;
        masc_log_message( MAS_VERBLVL_DEBUG, "mas: Process name too short, will not have status information.");
        return mas_error(MERR_INVALID);
    }

    if ( active )
    {
        _procstat_active = TRUE;
        masc_log_message( MAS_VERBLVL_DEBUG, "mas: Process name will have status information.");
        _procstat_argv0 = argv0;
        memset(_procstat_argv0, 0, _procstat_argv0_len );
        strcpy(_procstat_argv0, _procstat_prefix );
    }
    else
    {
        _procstat_active = FALSE;
        masc_log_message( MAS_VERBLVL_DEBUG, "mas: Process will not have status information.");
    }
    
    return 0;
}

int32
procstat_update( char* status )
{
    if ( !_procstat_active )
        return 0;
    
    if ( _procstat_argv0_len < strlen( status ) + _procstat_prefix_len )
        return mas_error(MERR_BOUNDS);
    memset(_procstat_argv0 + _procstat_prefix_len, 0, _procstat_argv0_len - _procstat_prefix_len );
    strcpy( _procstat_argv0 + _procstat_prefix_len, status );
    return 0;
}
