/*
    SPDX-FileCopyrightText: 2014-2023 Anne Jan Brouwer <brouwer@annejan.com>
    SPDX-FileCopyrightText: 2023 g10 Code GmbH
    SPDX-FileContributor: Sune Stolborg Vuorela <sune@vuorela.dk>

    SPDX-License-Identifier: GPL-3.0-or-later
*/
#include "util.h"
#include <QDir>
#include <QFileInfo>

/**
 * @brief Util::findPasswordStore look for common .password-store folder
 * location.
 * @return
 */
QString Util::findPasswordStore()
{
    QString path;
    if (qEnvironmentVariableIsSet("PASSWORD_STORE_DIR")) {
        path = qEnvironmentVariable("PASSWORD_STORE_DIR");
    } else {
#ifdef Q_OS_WIN
        path = QDir::homePath() + QLatin1Char('/') + QStringLiteral("password-store") + QLatin1Char('/');
#else
        path = QDir::homePath() + QLatin1Char('/') + QStringLiteral(".password-store") + QLatin1Char('/');
#endif
    }
    return Util::normalizeFolderPath(path);
}

/**
 * @brief Util::normalizeFolderPath let's always end folders with a
 * /
 * @param path
 * @return
 */
QString Util::normalizeFolderPath(QString path)
{
    if (!path.endsWith(QLatin1Char('/')))
        path += QLatin1Char('/');
    return path;
}

/**
 * @brief Util::copyDir
 * @param src
 * @param dest
 */
void Util::copyDir(const QString &src, const QString &dest)
{
    QDir srcDir(src);
    if (!srcDir.exists()) {
        return;
    }
    srcDir.mkpath(dest);
    const auto srcDirs = srcDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    for (const QString &dir : srcDirs) {
        copyDir(src + QLatin1Char('/') + dir, dest + QLatin1Char('/') + dir);
    }

    const auto srcFiles = srcDir.entryList(QDir::Files);
    for (const QString &file : srcFiles) {
        QFile::copy(src + QLatin1Char('/') + file, dest + QLatin1Char('/') + file);
    }
}

const QRegularExpression &Util::endsWithGpg()
{
    static const QRegularExpression expr{QStringLiteral("\\.gpg$")};
    return expr;
}

const QRegularExpression &Util::protocolRegex()
{
    static const QRegularExpression regex{QStringLiteral("((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://\\S+)")};
    return regex;
}
