/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Copyright (C) 2015 Petroules Corporation.
** Contact: http://www.qt.io/licensing
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "shellutils.h"
#include <QFile>
#include <QRegExp>
#include <QTextStream>

namespace qbs {
namespace Internal {

QString shellInterpreter(const QString &filePath) {
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly)) {
        QTextStream ts(&file);
        const QString shebang = ts.readLine();
        if (shebang.startsWith(QLatin1String("#!"))) {
            return (shebang.mid(2).split(QRegExp(QLatin1String("\\s")),
                                         QString::SkipEmptyParts) << QString()).first();
        }
    }

    return QString();
}

// isSpecialChar, hasSpecialChars, shellQuoteUnix, shellQuoteWin:
// all from qtbase/qmake/library/ioutils.cpp

inline static bool isSpecialChar(ushort c, const uchar (&iqm)[16])
{
    if ((c < sizeof(iqm) * 8) && (iqm[c / 8] & (1 << (c & 7))))
        return true;
    return false;
}

inline static bool hasSpecialChars(const QString &arg, const uchar (&iqm)[16])
{
    for (int x = arg.length() - 1; x >= 0; --x) {
        if (isSpecialChar(arg.unicode()[x].unicode(), iqm))
            return true;
    }
    return false;
}

static QString shellQuoteUnix(const QString &arg)
{
    // Chars that should be quoted (TM). This includes:
    static const uchar iqm[] = {
        0xff, 0xff, 0xff, 0xff, 0xdf, 0x07, 0x00, 0xd8,
        0x00, 0x00, 0x00, 0x38, 0x01, 0x00, 0x00, 0x78
    }; // 0-32 \'"$`<>|;&(){}*?#!~[]

    if (!arg.length())
        return QString::fromLatin1("''");

    QString ret(arg);
    if (hasSpecialChars(ret, iqm)) {
        ret.replace(QLatin1Char('\''), QLatin1String("'\\''"));
        ret.prepend(QLatin1Char('\''));
        ret.append(QLatin1Char('\''));
    }
    return ret;
}

static QString shellQuoteWin(const QString &arg)
{
    // Chars that should be quoted (TM). This includes:
    // - control chars & space
    // - the shell meta chars "&()<>^|
    // - the potential separators ,;=
    static const uchar iqm[] = {
        0xff, 0xff, 0xff, 0xff, 0x45, 0x13, 0x00, 0x78,
        0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x10
    };
    // Shell meta chars that need escaping.
    static const uchar ism[] = {
        0x00, 0x00, 0x00, 0x00, 0x40, 0x03, 0x00, 0x50,
        0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x10
    }; // &()<>^|

    if (!arg.length())
        return QString::fromLatin1("\"\"");

    QString ret(arg);
    if (hasSpecialChars(ret, iqm)) {
        // The process-level standard quoting allows escaping quotes with backslashes (note
        // that backslashes don't escape themselves, unless they are followed by a quote).
        // Consequently, quotes are escaped and their preceding backslashes are doubled.
        ret.replace(QRegExp(QLatin1String("(\\\\*)\"")), QLatin1String("\\1\\1\\\""));
        // Trailing backslashes must be doubled as well, as they are followed by a quote.
        ret.replace(QRegExp(QLatin1String("(\\\\+)$")), QLatin1String("\\1\\1"));
        // However, the shell also interprets the command, and no backslash-escaping exists
        // there - a quote always toggles the quoting state, but is nonetheless passed down
        // to the called process verbatim. In the unquoted state, the circumflex escapes
        // meta chars (including itself and quotes), and is removed from the command.
        bool quoted = true;
        for (int i = 0; i < ret.length(); i++) {
            QChar c = ret.unicode()[i];
            if (c.unicode() == '"')
                quoted = !quoted;
            else if (!quoted && isSpecialChar(c.unicode(), ism))
                ret.insert(i++, QLatin1Char('^'));
        }
        if (!quoted)
            ret.append(QLatin1Char('^'));
        ret.append(QLatin1Char('"'));
        ret.prepend(QLatin1Char('"'));
    }
    return ret;
}

QString shellQuote(const QString &arg, HostOsInfo::HostOs os)
{
    return os == HostOsInfo::HostOsWindows ? shellQuoteWin(arg) : shellQuoteUnix(arg);
}

QString shellQuote(const QString &program, const QStringList &args, HostOsInfo::HostOs os)
{
    QString result = shellQuote(program, os);
    foreach (const QString &arg, args) {
        result += QLatin1Char(' ') + shellQuote(arg, os);
    }
    return result;
}

} // namespace Internal
} // namespace qbs
