#include <vo_stdio.h>
#include <string.h>
#include <sysmemory.h>
#include <extSymbols.h>
#include "env.h"

int SetEnv(register const char *name, register const char *value) {
  int res = -1;
  struct ExtSymbol __mem_y *sym;
  struct EnvVariable *env = NULL;

#if 0
  printf("SE #1 %s = %s\n", name, value);
#endif
  ClearEnv(name);
#if 0
  printf("SE #2\n");
#endif
  sym = AddSymbol(name, (void *)2, NULL);
#if 0
  printf("SE #2.5 SZ = %d, sym %x\n", sizeof(struct EnvVariable), sym);
#endif
  if (sym) {
    int len1 = strlen(name), len2 = strlen(value);
    env = malloc(sizeof(struct EnvVariable)+len1+len2+1);
    if (env) {
      env->value = (char *)env + sizeof(struct EnvVariable) + len1;
#if 0
      printf("SE #3, name %x, val %x\n", env->name, env->value);
#endif
      strcpy(env->value, value);
      strcpy(env->name, name);
      sym->addr = (u_int16)env;
      res = 0;
    }
  }
#if 0
  printf("SE #4\n");
#endif
 finally:
#if 0
  printf("SE #5\n");
#endif
  if (res) {
#if 0
    printf("SE #6\n");
#endif
    if (sym) {
#if 0
      printf("SE #7\n");
#endif
      SymbolDelete(SymbolCrunchStringCalcCrc32(name));
      sym = NULL;
    }
  }
#if 0
  printf("SE #8\n");
#endif
  return res;
}


int GetEnv(register const char *name, register char *d, register int dSize) {
  u_int32 crc32 = SymbolCrunchStringCalcCrc32(name);
  struct ExtSymbol __mem_y *sym = SymbolFindByCrc(crc32);
  if (sym && (int)(sym->lib) == 2) {
    struct EnvVariable *env = (void *)sym->addr;
    int len = strlen(env->value);
    if (len >= dSize) len = dSize-1;
    memcpy(d, env->value, len);
    d[len] = '\0';
    return len;
  }
  return -1;
}


int ClearEnv(register const char *name) {
  int res = -1;
  u_int32 crc32 = SymbolCrunchStringCalcCrc32(name);
  struct ExtSymbol __mem_y *sym = SymbolFindByCrc(crc32);
#if 0
  printf("CE #1, name = %s, crc %08lx, sym %x\n", name, crc32, sym);
#endif
  if (sym && (int)(sym->lib) == 2) {
    struct EnvVariable *env = (void *)sym->addr;
#if 0
    printf("CE #2, env = %x, name = %s, val = %x\n", env, name, env->value);
#endif
    if (env) free(env);
    env = NULL;
    if (SymbolDelete(crc32) == 1) res = 0;
#if 0
    printf("CE #2.7, res = %d\n", res);
#endif
    goto finally;
  } else {
#if 0
    printf("CE #3\n");
#endif
    goto finally;
  }

#if 0
  printf("CE #4\n");
#endif
  res = 0;
 finally:
#if 0
  printf("CE #5\n");
#endif
  return res;
}

