/*
 *  This file is part of ixemul.library for the Amiga.
 *  Copyright (C) 1991, 1992  Markus M. Wild
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#define KERNEL
#include "ixemul.h"

#define alloca __builtin_alloca

#define BASE_EXT_DECL
#define BASE_PAR_DECL	
#define BASE_PAR_DECL0	
#define BASE_NAME	ix.ix_dos_base
__inline static BOOL SetVar(BASE_PAR_DECL UBYTE* name, UBYTE* buffer, long int size, long int flags)
{
	BASE_EXT_DECL
	register BOOL res __asm("d0");
	register void *a6 __asm ("a6");
	register UBYTE* d1 __asm("d1");
	register UBYTE* d2 __asm("d2");
	register long int d3 __asm("d3");
	register long int d4 __asm("d4");

	a6 = BASE_NAME;
	d1 = name;
	d2 = buffer;
	d3 = size;
	d4 = flags;
	__asm volatile ("
	jsr a6@(-0x384)"
	: "=r" (res)
	: "r" (a6), "r" (d1), "r" (d2), "r" (d3), "r" (d4)
	: "d0", "d1", "a0", "a1", "d2", "d3", "d4");
	return res;
}

extern int _dos20;

int
setenv (const char *var, const char *val, ...)
{
  int fd;
  char *name;
  int result = -1;
  int omask;

  /* under 2.0, use the system function */
  if (_dos20)
    {
      /* but when using the system, block signals, sigh.. */
      omask = syscall (SYS_sigsetmask , ~0);
      result = SetVar (var, val, -1, 0) ? 0 : -1;
      syscall (SYS_sigsetmask, omask);
      return result;
    }
  else
    {
      name = alloca (strlen(var) + sizeof("env:") + 1);
      strcpy(name, "env:");
      strcat(name, var);
      fd = syscall (SYS_open, name, O_WRONLY|O_CREAT|O_TRUNC, 0666);
      if (fd >= 0)
        {
          syscall (SYS_write, fd, val, strlen (val));
          syscall (SYS_close, fd);
          result = 0;
        }
      return result;
    }
}
