#define _POSIX_C_SOURCE 200112L
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

extern char **environ;

static void die(const char *s)
{
    perror(s);
    exit(1);
}

static char *xstrdup(const char *s)
{
    char *p;

    p = malloc(strlen(s) + 1);
    if (p == NULL)
        die("malloc");
    strcpy(p, s);
    return (p);
}

static void dump_proc(const char *title)
{
    int fd;
    char buf[4096];
    ssize_t n;
    ssize_t i;
    ssize_t start;
    fd = open("/proc/self/environ", O_RDONLY);
    if (fd < 0)
        die("open");
    n = read(fd, buf, sizeof(buf));
    close(fd);
    if (n < 0)
        die("read");
    printf("\n== %s ==\n", title);
    start = 0;
    i = 0;
    while (i < n) {
        if (buf[i] == '\0' && i > start)
            printf("%.*s\n", (int)(i - start), buf + start);
        if (buf[i] == '\0')
            start = i + 1;
        i++;
    }
}

static size_t env_span(char **env, char **out)
{
    char *start;
    char *end;
    char *e;
    int i;

    if (env == NULL || env[0] == NULL)
        return (*out = NULL, 0);
    start = env[0];
    end = env[0] + strlen(env[0]) + 1;
    i = 1;
    while (env[i] != NULL) {
        e = env[i] + strlen(env[i]) + 1;
        if (env[i] < start)
            start = env[i];
        if (e > end)
            end = e;
        i++;
    }
    *out = start;
    return ((size_t)(end - start));
}

static void move_env(void)
{
    char **copy;
    int i;
    int n;

    n = 0;
    while (environ[n] != NULL)
        n++;
    copy = malloc((n + 1) * sizeof(*copy));
    if (copy == NULL)
        die("malloc");
    i = 0;
    while (i < n) {
        copy[i] = xstrdup(environ[i]);
        i++;
    }
    copy[n] = NULL;
    environ = copy;
}

static void put(char *block, size_t len, size_t *pos, const char *s)
{
    size_t n;

    n = strlen(s) + 1;
    if (*pos + n > len)
        return ;
    memcpy(block + *pos, s, n);
    *pos += n;
}

int main(void)
{
    char *old;
    size_t len;
    size_t pos;

    old = NULL;
    len = env_span(environ, &old);
    printf("pid = %ld\n", (long)getpid());
    dump_proc("1) start");
    setenv("ADDED_BY_SETENV", "yes", 1);
    unsetenv("SECOND");
    printf("\ngetenv ADDED_BY_SETENV = %s\n", getenv("ADDED_BY_SETENV"));
    printf("getenv SECOND = %s\n",
        getenv("SECOND") ? getenv("SECOND") : "null");
    dump_proc("2) after setenv/unsetenv");
    move_env();
    memset(old, 0, len);
    pos = 0;
    put(old, len, &pos, "PROC_ENV=changed");
    put(old, len, &pos, "X=1");
    dump_proc("3) after direct overwrite");
    return (0);
}
