/*
    Copyright 2016 Gleb Popov <6yearold@gmail.com>
    Copyright (c) 2023 Serenity Cyber Security, LLC <license@futurecrew.ru>
                Author: Alexey Yushkin <x636808@gmail.com>

    Redistribution and use in source and binary forms, with or without modification,
    are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors may
    be used to endorse or promote products derived from this software without specific
    prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
    ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <sys/stat.h>

#include <QFileInfo>

#include <ranges>

#include "bsdisks.h"
#include "block.h"
#include "drive.h"
#include "objectmanager.h"

namespace views = std::views;

inline QByteArray devPath(const QString device)
{
    return (QStringLiteral("/dev/") + device).toLocal8Bit();
}

Block::Block(QObject* parent) :
    QObject(parent), bFilesystem(nullptr),
    bPartition(nullptr), bPartTable(nullptr), needsAnotherProbe(false),
    registered(false), hasNoDrive(false)
{
}

QString Block::id() const
{
    if(bPartition)
    {
        auto tableType = bPartition->partTableBlock->bPartTable->tableType();
        QChar partitionSymbol = tableType == QStringLiteral("gpt")
                                ? 'p'
                                : 's';
        return bPartition->partTableBlock->id() + "_" + name.mid(name.lastIndexOf(partitionSymbol));
    }
    else
        return description + "_" + identifier;
}


QString Block::idLabel() const
{
    if(bFilesystem && bFilesystem->filesystem == "zfs")
        return bFilesystem->zfsDataset;

    if(labels.empty())
        return QString();

    QString ret = labels[0];

    for(const auto& label: labels)
        if(label.startsWith("ufs/")) {
            ret = label;
            break;
        }

    ret = ret.mid(ret.lastIndexOf('/') + 1);
    return QUrl::fromPercentEncoding(ret.toLatin1());
}

QString Block::driveName() const
{
    if(bPartition)
        return bPartition->partTableBlock->driveName();

    return name;
}


QDBusObjectPath Block::drive() const
{
    return QDBusObjectPath(UDisksDrives + driveName());
}

QByteArray Block::preferredDevice() const
{
    if(labels.empty())
        return device();
    return devPath(labels[0]) + '\0';
}


QByteArray Block::device() const
{
    return devPath(name) + '\0';
}


qulonglong Block::deviceNumber() const
{
    struct stat st;

    ::stat(devPath(name).constData(), &st);
    return st.st_rdev;
}


QByteArrayList Block::symlinks()
{
    QByteArrayList ret;
    std::transform(labels.begin(), labels.end(),
        std::back_inserter(ret), [](const auto& label) {
            return devPath(label) + '\0';
        }
    );
    return ret;
}


qulonglong Block::blockSize() const
{
    return bPartition ? bPartition->size : size;
}

bool Block::hintIgnore() const
{
    if(bPartition && parentDrive)
    {
        // there should be better predicate for this, probably
        if(bPartition->partitionType == "efi" && parentDrive->connectionBus() != "usb")
            return true;
    }

    return false;
}

QString Block::hintName() const
{
    return idLabel();
}

QByteArrayList Block::mountPoints() const
{
    QByteArrayList ret;

    if(bFilesystem)
    {
        auto mounts = bFilesystem->mountPoints;
        std::transform(mounts.begin(), mounts.end(),
            std::back_inserter(ret), [](const auto& pair) {
                return pair.first + '\0';
            }
        );
    }

    return ret;
}


QString Block::partitionTableType()
{
    if(!bPartTable)
        return QString();

    return bPartTable->tableType();
}


QString Block::partitionName() const
{
    if(!bPartition)
        return QString();

    return bPartition->name();
}


QString Block::uuid() const
{
    if(!bPartition)
        return QString();

    return bPartition->uuid;
}


uint Block::number() const
{
    if(!bPartition)
        return 0;

    return bPartition->number;
}


qulonglong Block::offset() const
{
    if(!bPartition)
        return 0;

    return bPartition->offset;
}


qulonglong Block::partitionSize() const
{
    if(!bPartition)
        return 0;

    return bPartition->size;
}


QString Block::partitionType() const
{
    if(!bPartition)
        return 0;

    return bPartition->partitionType;
}


QDBusObjectPath Block::table() const
{
    if(!bPartition)
        return QDBusObjectPath("/");

    return bPartition->partTableBlock->dbusPath;
}

void Block::fillMountPoints()
{
    auto readyStorage = QStorageInfo::mountedVolumes()
        | views::filter([](const QStorageInfo &storage) { return storage.isValid() && storage.isReady(); });
    for (const QStorageInfo &storage : readyStorage)
    {
        // first check if the mounted device matches this->device()
        bool match = !storage.device().compare(device().chopped(1));
        // then go over all labels
        for(const auto& label : labels)
        {
            if(match)
                break;

            match = !storage.device().compare(devPath(label));
        }

        if(match)
            bFilesystem->mountPoints << qMakePair(storage.rootPath().toLocal8Bit(), 0);
    }
}

void Block::Rescan(const QVariantMap& options)
{
    ObjectManager::Instance().startFilesystemProbe(this);
}
