/******************************************************************************
 *
 * Copyright (c) 2017, the Perspective Authors.
 *
 * This file is part of the Perspective library, distributed under the terms of
 * the Apache License 2.0.  The full license can be found in the LICENSE file.
 *
 */

#include <perspective/first.h>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <perspective/raw_types.h>
#include <string>
#include <sstream>
#include <sstream>
#include <iomanip>
#ifndef WIN32
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#endif
namespace perspective
{

t_str
unique_path(const t_str& path_prefix)
{
    std::stringstream ss;
    ss << path_prefix << boost::uuids::random_generator()();
    return ss.str();
}

t_str
str_(int value, const t_str& fill, t_int32 width)
{
    std::stringstream ss;
    ss << std::setfill('0') << std::setw(width) << value;
    return ss.str();
}

t_str
str_(int value)
{
    return str_(value, "0", 2);
}

std::vector<t_str>
split(const t_str& s, char delim)
{
    std::vector<t_str> elems;
    std::stringstream ss;
    ss.str(s);
    t_str item;
    while (std::getline(ss, item, delim))
    {
        if (!item.empty())
            elems.push_back(item);
    }
    return elems;
}

#ifdef WIN32
void print_trace() { }
#else

void print_trace() {
    char pid_buf[30];
    sprintf(pid_buf, "%d", getpid());
    char name_buf[512];
    name_buf[readlink("/proc/self/exe", name_buf, 511)]=0;
    int child_pid = fork();
    if (!child_pid) {           
        dup2(2,1); // redirect output to stderr
        fprintf(stdout,"stack trace for %s pid=%s\n",name_buf,pid_buf);
        execlp("gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL);
        abort(); /* If gdb failed to start */
    } else {
        waitpid(child_pid,NULL,0);
    }
}
#endif
} // namespace perspective
