/*	recipe.c
 *  (c) Copyright 1991 by Ben Eng, All Rights Reserved
 *
 */

#include <clib/exec_protos.h>
#include <clib/dos_protos.h>

#include <string.h>
#include <ctype.h>

#include "make.h"
#include "depend.h"

/* execute the command List to make a target */
int
recipe( const char *goalname, struct List *cmdlist )
{
	char cd_string[ 10 ];
	struct command *cmd;
	char *expansion = NULL;
	char *next;
	int retval = 0;

	if( !cmdlist ) return( 0 ); /* no command list */

	if( Param.touch_mode ) {
		logprintf( "\ttouch(%s)\n", goalname );
		if( !Param.pretend_mode ) touch( goalname );
		return( 0 );
	}

	expansion = (char *)malloc( Param.MaxLine );

	for( cmd = (struct command *) cmdlist->lh_Head;	cmd->node.ln_Succ;
		cmd = cmd->node.ln_Succ ) {
		if( next = cmd->cmd )
			while( isspace( *next )) next++;
		if( next && *next ) {
			if( expand_macros( expansion, next, Param.MaxLine )) {
				logprintf( "Error expanding macros on commandline:\n"
					"\t%s\n", next );
				break;
			};
			if( !(cmd->flags & CF_NOECHO ) || Param.debug )
				logprintf( "\t%s\n", expansion );
			parse_str( cd_string, expansion, 10 );
			if( !strcmp( cd_string, "cd" )) {
				logprintf( "the \"cd\" command does not work\n" );
				break;
			}
			retval = (Param.pretend_mode ) ? 0 :xsystem( expansion );
			if( retval ) {
				char *s = (cmd->flags & CF_IGNORE ) ? "(Ignored)" : "" ;
				logprintf( "command returned error %d %s\n", retval, s );
				if( !(cmd->flags & CF_IGNORE )) break;
			}
		}
	}
	if( expansion ) free( expansion );
	return( retval );
}
