/*
-----BEGIN QCMOD-----
name: certstore
section: project
arg: certstore-path=[path],Path to the SSL/X509 Certificate store file.
arg: certstore-internal,Force the use of the bundled store.
-----END QCMOD-----
*/

class qc_certstore : public ConfObj
{
public:
	qc_certstore(Conf *c) : ConfObj(c) {}
	QString name() const { return "certstore"; }
	QString shortname() const { return "certstore"; }

	bool exec()
	{
		bundled = false;

#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
		// use built-in
		return true;
#else
		if(conf->getenv("QC_CERTSTORE_INTERNAL") != "Y")
		{
			QStringList pathsToTry;

			path = conf->getenv("QC_CERTSTORE_PATH");
			if(!path.isEmpty())
			{
				conf->addExtra(makeEscapedDefine("QCA_SYSTEMSTORE_PATH", path));
				return true;
			}

			// This is from Debian
			pathsToTry.append( QString("/etc/ssl/certs/ca-certificates.crt") );

			// Fedora Core 2 uses these
			pathsToTry.append( QString("/usr/share/ssl/cert.pem") );
			pathsToTry.append( QString("/usr/share/ssl/certs/ca-bundle.crt") );

			// Fedora Core 5 changes to this
			pathsToTry.append( QString("/etc/pki/tls/cert.pem") );

			for(int n = 0; n < pathsToTry.count(); ++n)
			{
        			if(QFile::exists(pathsToTry[n]))
				{
					path = pathsToTry[n];
					break;
				}
			}
		}

		// fall back to bundled
		if(path.isEmpty())
		{
			// --prefix=$pwd ?
			if(QFile::exists(conf->getenv("PREFIX") + "/certs/rootcerts.pem"))
				path = "$$PREFIX/certs/rootcerts.pem";
			else
				path = "$$DATADIR/qca/certs/rootcerts.pem";

			QString extra =
			"sharedfiles.path = $$DATADIR/qca\n"
			"sharedfiles.files = certs\n"
			"INSTALLS += sharedfiles\n";
			conf->addExtra(extra);
			bundled = true;
		}

		conf->addExtra(makeEscapedDefine("QCA_SYSTEMSTORE_PATH", path));

		return true;
#endif
	}

	QString makeEscapedDefine(const QString &var, const QString &val)
	{
		QString str = QString(
		"DEFINES += %1=\\\\\\\\\\\\\\"%2\\\\\\\\\\\\\\"\n"
		).arg(var).arg(val);
		return str;
	}

	QString resultString() const
	{
#if defined(Q_OS_WIN)
		return "using Windows built-in";
#elif defined(Q_OS_MAC)
		return "using Mac built-in";
#else
		if(success)
		{
			if(bundled)
				return "using bundled";
			else
				return path;
		}
		else
			return ConfObj::resultString();
#endif
	}

private:
	QString path;
	bool bundled;
};
