/*
  ==============================================================================

   This file is part of the JUCE framework.
   Copyright (c) Raw Material Software Limited

   JUCE is an open source framework subject to commercial or open source
   licensing.

   By downloading, installing, or using the JUCE framework, or combining the
   JUCE framework with any other source code, object code, content or any other
   copyrightable work, you agree to the terms of the JUCE End User Licence
   Agreement, and all incorporated terms including the JUCE Privacy Policy and
   the JUCE Website Terms of Service, as applicable, which will bind you. If you
   do not agree to the terms of these agreements, we will not license the JUCE
   framework to you, and you must discontinue the installation or download
   process and cease use of the JUCE framework.

   JUCE End User Licence Agreement: https://juce.com/legal/juce-8-licence/
   JUCE Privacy Policy: https://juce.com/juce-privacy-policy
   JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/

   Or:

   You may also use this code under the terms of the AGPLv3:
   https://www.gnu.org/licenses/agpl-3.0.en.html

   THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
   WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
   MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

enum
{
    U_ISOFS_SUPER_MAGIC = 0x9660,   // linux/iso_fs.h
    U_MSDOS_SUPER_MAGIC = 0x4d44,   // linux/msdos_fs.h
    U_NFS_SUPER_MAGIC = 0x6969,     // linux/nfs_fs.h
    U_SMB_SUPER_MAGIC = 0x517B      // linux/smb_fs.h
};

bool File::isOnCDRomDrive() const
{
    struct statfs buf;

    return statfs (getFullPathName().toUTF8(), &buf) == 0
             && buf.f_type == (unsigned int) U_ISOFS_SUPER_MAGIC;
}

bool File::isOnHardDisk() const
{
    struct statfs buf;

    if (statfs (getFullPathName().toUTF8(), &buf) == 0)
    {
        switch (buf.f_type)
        {
            case U_ISOFS_SUPER_MAGIC:   // CD-ROM
            case U_MSDOS_SUPER_MAGIC:   // Probably floppy (but could be mounted FAT filesystem)
            case U_NFS_SUPER_MAGIC:     // Network NFS
            case U_SMB_SUPER_MAGIC:     // Network Samba
                return false;

            default: break;
        }
    }

    // Assume so if this fails for some reason
    return true;
}

bool File::isOnRemovableDrive() const
{
    jassertfalse; // xxx not implemented for linux!
    return false;
}

String File::getVersion() const
{
    return {}; // xxx not yet implemented
}

//==============================================================================
static File resolveXDGFolder (const char* const type, const char* const fallbackFolder)
{
    StringArray confLines;
    File ("~/.config/user-dirs.dirs").readLines (confLines);

    for (int i = 0; i < confLines.size(); ++i)
    {
        const String line (confLines[i].trimStart());

        if (line.startsWith (type))
        {
            // eg. resolve XDG_MUSIC_DIR="$HOME/Music" to /home/user/Music
            const File f (line.replace ("$HOME", File ("~").getFullPathName())
                              .fromFirstOccurrenceOf ("=", false, false)
                              .trim().unquoted());

            if (f.isDirectory())
                return f;
        }
    }

    return File (fallbackFolder);
}

const char* const* juce_argv = nullptr;
int juce_argc = 0;

File File::getSpecialLocation (const SpecialLocationType type)
{
    switch (type)
    {
        case userHomeDirectory:
        {
            if (const char* homeDir = getenv ("HOME"))
                return File (CharPointer_UTF8 (homeDir));

            if (auto* pw = getpwuid (getuid()))
                return File (CharPointer_UTF8 (pw->pw_dir));

            return {};
        }

        case userDocumentsDirectory:          return resolveXDGFolder ("XDG_DOCUMENTS_DIR", "~/Documents");
        case userMusicDirectory:              return resolveXDGFolder ("XDG_MUSIC_DIR",     "~/Music");
        case userMoviesDirectory:             return resolveXDGFolder ("XDG_VIDEOS_DIR",    "~/Videos");
        case userPicturesDirectory:           return resolveXDGFolder ("XDG_PICTURES_DIR",  "~/Pictures");
        case userDesktopDirectory:            return resolveXDGFolder ("XDG_DESKTOP_DIR",   "~/Desktop");
        case userApplicationDataDirectory:    return resolveXDGFolder ("XDG_CONFIG_HOME",   "~/.config");
        case commonDocumentsDirectory:
        case commonApplicationDataDirectory:  return File ("/opt");
        case globalApplicationsDirectory:     return File ("/usr");

        case tempDirectory:
        {
            if (const char* tmpDir = getenv ("TMPDIR"))
                return File (CharPointer_UTF8 (tmpDir));

            return File ("/tmp");
        }

        case invokedExecutableFile:
            if (juce_argv != nullptr && juce_argc > 0)
                return File (String (CharPointer_UTF8 (juce_argv[0])));
            // Falls through
            JUCE_FALLTHROUGH

        case currentExecutableFile:
        case currentApplicationFile:
        {
            const auto f = juce_getExecutableFile();
            return f.isSymbolicLink() ? f.getLinkedTarget() : f;
        }

        case hostApplicationPath:
        {
           #if JUCE_BSD
            return juce_getExecutableFile();
           #else
            const File f ("/proc/self/exe");
            return f.isSymbolicLink() ? f.getLinkedTarget() : juce_getExecutableFile();
           #endif
        }

        default:
            jassertfalse; // unknown type?
            break;
    }

    return {};
}

//==============================================================================
bool File::moveToTrash() const
{
    if (! exists())
        return true;

    static auto gio = std::invoke ([]
    {
        DynamicLibrary lib;

        if (lib.open ("libgio-2.0.so.0") || lib.open ("libgio-2.0.so"))
            return lib;

        // Maybe the GLib/gio library isn't installed?
        // This might be innocent if you're running on a minimal or embedded
        // install or if no desktop environment is installed.
        jassertfalse;
        return lib;
    });

    if (! gio.isOpen())
        return false;

    static const auto g_file_new_for_path = gio.getFunction<void* (const char*)> ("g_file_new_for_path");
    static const auto g_object_unref = gio.getFunction<void (void*)> ("g_object_unref");
    static const auto g_file_trash = gio.getFunction<int (void*, void*, void*)> ("g_file_trash");

    if (g_file_new_for_path == nullptr
        || g_object_unref == nullptr
        || g_file_trash == nullptr)
    {
        // Symbols failed to load!
        // Please let the JUCE team know if you encounter this assertion.
        jassertfalse;
        return false;
    }

    void* file = g_file_new_for_path (fullPath.toRawUTF8());
    const ScopeGuard scope { [&] { g_object_unref (file); } };

    return (bool) g_file_trash (file, nullptr, nullptr);
}

//==============================================================================
static bool isFileExecutable (const String& filename)
{
    juce_statStruct info;

    return juce_stat (filename, info)
            && S_ISREG (info.st_mode)
            && access (filename.toUTF8(), X_OK) == 0;
}

bool Process::openDocument (const String& fileName, const String& parameters)
{
    const auto cmdString = [&]
    {
        if (fileName.startsWithIgnoreCase ("file:")
            || File::createFileWithoutCheckingPath (fileName).isDirectory()
            || ! isFileExecutable (fileName))
        {
            const auto singleCommand = fileName.trim().quoted();

            StringArray cmdLines;

            for (auto browserName : { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla",
                                      "google-chrome", "chromium-browser", "opera", "konqueror" })
            {
                cmdLines.add (String (browserName) + " " + singleCommand);
            }

            return cmdLines.joinIntoString (" || ");
        }

        return (fileName.replace (" ", "\\ ", false) + " " + parameters).trim();
    }();

    const char* const argv[] = { "/bin/sh", "-c", cmdString.toUTF8(), nullptr };

    const auto cpid = fork();

    if (cpid == 0)
    {
        setsid();

        // Child process
        execv (argv[0], (char**) argv);
        exit (0);
    }

    return cpid >= 0;
}

void File::revealToUser() const
{
    if (isDirectory())
        startAsProcess();
    else if (getParentDirectory().exists())
        getParentDirectory().startAsProcess();
}

} // namespace juce
