/*
    libmaus2
    Copyright (C) 2009-2020 German Tischler
    Copyright (C) 2011-2013 Genome Research Limited

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <libmaus2/network/GetHostName.hpp>
#include <libmaus2/autoarray/AutoArray.hpp>
#include <cerrno>

#if defined(LIBMAUS2_HAVE_WINSOCK2_H)
#include <winsock2.h>
#endif

#if defined(LIBMAUS2_HAVE_UNISTD_H)
#include <unistd.h>
#endif

std::string libmaus2::network::GetHostName::getHostName()
{
        #if defined(LIBMAUS2_HAVE_GETHOSTNAME)
        ::libmaus2::autoarray::AutoArray<char> hostnamebuf(1025);
        if ( gethostname(hostnamebuf.get(),hostnamebuf.size()-1) != 0 )
        {
                #if defined(LIBMAUS2_HAVE_WINSOCK2_H)
                int const error = WSAGetLastError();
                libmaus2::autoarray::AutoArray<char> amsgbuf(1024);

                FormatMessage (
                    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                    nullptr,
                    error,
                    MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
                    amsgbuf.begin(),
                    amsgbuf.size(),
                    nullptr
                );

                ::libmaus2::exception::LibMausException se;
                se.getStream() << "gethostname() failed: " << amsgbuf.begin() << std::endl;
                se.finish();
                throw se;
                #else
                ::libmaus2::exception::LibMausException se;
                se.getStream() << "gethostname() failed: " << strerror(errno) << std::endl;
                se.finish();
                throw se;
                #endif
        }

        std::string const shostname(hostnamebuf.get());

        return shostname;
        #else
        ::libmaus2::exception::LibMausException se;
        se.getStream() << "gethostname() system call not supported" << std::endl;
        se.finish();
        throw se;
        #endif
}
