#ifndef IVBACKTRACE_H
#define IVBACKTRACE_H

#include <QtCore/qglobal.h>


//#define USE_BOOSTBACKTRACE  //if USE_BOOSTBACKTRACE LIBS += -ldl LIBS += -lboost_system -lboost_filesystem -lbacktrace

#if defined(IVBACKTRACE_LIBRARY)
#  define IVBACKTRACE_EXPORT Q_DECL_EXPORT
#else
#  define IVBACKTRACE_EXPORT Q_DECL_IMPORT
#endif

#ifndef USE_BOOSTBACKTRACE


void RegisterIVBackTrace();


#else


#ifdef Q_OS_LINUX

#ifndef  BOOST_STACKTRACE_USE_BACKTRACE
#define BOOST_STACKTRACE_USE_BACKTRACE
#endif

#endif

#include <string>
#include <boost/noncopyable.hpp>
#include <boost/function.hpp>
#include <boost/stacktrace.hpp>

#include <signal.h>     // ::signal, ::raise
// #include <strstream>
#include <stdexcept>    // std::logic_error
#include <iostream>     // std::cerr
#include <boost/filesystem.hpp>

#include <strstream>

#include <iostream>

#include <QFile>
#include <QDateTime>
#include <QDir>
/*
size_t get_executable_path( char* processdir,char* processname, size_t len)
{
        char* path_end;
        int nsize;
        if((nsize =readlink("/proc/self/exe", processdir,len)) <=0)
                return -1;

        processdir[nsize] = '\0';
        path_end = strrchr(processdir,  '/');
        if(path_end == NULL)
                return -1;
        ++path_end;


        strcpy(processname, path_end);
        *path_end = '\0';

        return (size_t)(path_end - processdir);
}
*/
void x_signal_handler(int signum) {
    ::signal(signum, SIG_DFL);

    std::ostrstream ostr;
    ostr<<boost::stacktrace::stacktrace()<<std::endl;
//    std::cout << boost::stacktrace::stacktrace()<<std::endl;


    char strpath[1024];
    QDateTime dt = QDateTime::currentDateTime();
    char path[1000];
    char processname[1024];
//    get_executable_path(path, processname, 1000);
    snprintf(strpath,255,"%s/log/%s-%d-%s.log",getenv("HOME"),processname, getpid(),dt.toString("yyyyMMddhhmmsszzz").toLatin1().data());

    char strdir[1024];
    snprintf(strdir,255,"%s/log",getenv("HOME"));
    QDir xdir;
    xdir.setPath(strdir);
    if(!xdir.exists())
    {
        qDebug("create dir %s",strdir);
        xdir.mkdir(strdir);
    }
    QFile xFile;
    xFile.setFileName(strpath);
    if(xFile.open(QIODevice::ReadWrite))
    {
        xFile.write(ostr.str());
    }
    else
    {
        std::cout<<ostr.str()<<std::endl;
    }
    xFile.close();
    ::raise(SIGABRT);
}

void RegisterIVBackTrace()
{
	std::ostrstream ostr;
    ostr << boost::stacktrace::stacktrace()<<std::endl;
    ::signal(SIGSEGV, &x_signal_handler);
//    ::signal(SIGABRT, &x_signal_handler);
}

#endif

#endif // IVBACKTRACE_H