#ifndef CONFIG_H
#define CONFIG_H

/*
 * @(#)Config.h
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 1999-2003 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 *
 * Jörg Haeger, 25.05.1999
 */

#include <stdio.h>
#include <string.h>
#include "Boolean.h"
#include "Error.h"
#include "File.h"
#include "Integer.h"
#include "Process.h"
#include "String.h"
#include "Support.h"
#include "Types.h"
#include "Log.h"

#include "config.h"

const int maxNumOfReaders = 10, maxNumOfWriters = 10;

/**
 * This class delivers the values of the configuration file.
 *
 * @version 20030310
 * @author Jörg P. M. Haeger
 */
class Config {
	public: String
		cdrdaoInfo,
		cdrecordInfo,
		mkisofsInfo,
		mpg123Info,
		ogg123Info,
		soxInfo;

	private: const char *configDir;
	const char *fileName;
	Exception *firstError;
	int numOfReaders, numOfWriters;
	String text;
	boolean HTML;
	const char *readerInfos[maxNumOfReaders];
	const char *writerInfos[maxNumOfWriters];

	// values
	boolean accounts;
	const char *accountsFile;
	boolean anonymousUse;
	boolean burnProof;
	const char *cdrdaoArgs;
	const char *cdrecordArgs;
	const char *CDROMs[maxNumOfReaders];
	boolean copySupport;
	const char *debug;
	const char *defaultFilesDir;
	int defaultSpeed;
	int DVDplusRWSupport[maxNumOfWriters];
	boolean ejectOnDone;
	boolean ejectOnReservation;
	const char *eMailOnError;
	boolean exportArchive;
	const char *ftpPubDir;
	gid_t gid;
	const char *group;
	const char *homeDir;
	const char *imageFile[maxNumOfWriters];
	boolean imageOnTheFly;
	const char *infoFile;
	boolean laserOn;
	const char *logDir;
	const char *logoURL;
	int logLevel;
	int maxCopies;
	int maxMBytesInSpoolDir;
	int maxMBytesPerSession;
	int maxOpenConnections;
	int maxOpenSessions;
	int maxSpeed;
	const char *mkisofsArgs;
	boolean MP3decoding;
	const char *organization;
	unsigned short int portNo;
	const char *readerRawDevices[maxNumOfReaders];
	boolean removeSessions;
	int reservedMBytes;
	const char *setSchedulerPath;
	boolean showUsers;
	const char *spoolDir;
	unsigned short int statusPortNo;
	uid_t uid;
	const char *user;
	boolean verify;
	const char *verifyPath;
	int waitForCD;
	const char *waitForCDMsgFile;
	const char *writers[maxNumOfWriters];
	const char *writerRawDevices[maxNumOfWriters];

	struct Item {
		String key;
		Object &default0, &config, &active, &example;
		boolean isConfig, isDefault;

		public: Item(const char *key, boolean value):
			key(key),
			default0(*new Boolean(value)),
			config(*new Boolean(false)),
			active(*new Boolean(value)),
			example(*new Boolean(false)) {
			isConfig = isDefault = false;
		}

		public: Item(const char *key, int value):
			key(key),
			default0(*new Integer(value)),
			config(*new Integer(-1)),
			active(*new Integer(value)),
			example(*new Integer(-1)) {
			isConfig = isDefault = false;
		}

		public: Item(const char *key, const char *value,
			const char *example = ""):
			key(key),
			default0(*new String(value)),
			config(*new String()),
			active(*new String(value)),
			example(*new String(example)) {
			isConfig = isDefault = false;
		}
	};
	Item *items[100];
	int numOfItems;

	public: Config();

/*	private: void activateDefaults() {
		for (int i = 0; i < numOfItems; i++) {
			items[i]->active = items[i]->default0;
			items[i]->isDefault = true;
		}
	}
*/
	private: int add(Item *item) {
		const char *key = item->key.getBytes();
		int index = search(key);
		if (index >= 0)
			throw new Exception(S.e + key + " already exists");

		for (index = 0; index < numOfItems; index++)
			if (items[index]->key.compareToIgnoreCase(key) > 0)
				break;

		for (int i = numOfItems; i > index; i--)
			items[i] = items[i - 1];

		numOfItems++;
		items[index] = item;
		items[index]->key = key;
		items[index]->isDefault = true;
		return index;
	}

	private: void add(const char *key, boolean value) {
		add(new Item(key, value));
	}

	private: void add(const char *key, const char *value) {
		add(new Item(key, value));
	}

	private: void add(const char *key, int value) {
		add(new Item(key, value));
	}

	private: void cdrecordInq(int writerNo);

	private: void cdrecordHelp() {
		Process p(getCdrecordPath());
		p.addArg("-help");
		p.start();

		while (1) {
			const char *lineStr = p.readLine();
			if (lineStr == NULL)
				break;

			if (strstr(lineStr, "gracetime=#") != NULL)
				set("gracetime", 2);
		}
	}

	private: void cdrecordScanbus();

	private: void cdrecordVersion() {
		Process p(getCdrecordPath());
		p.addArg("-version");
		p.start();
		const char *lineStr = p.readLine();
		if (lineStr == NULL)
			throw new Exception("can't run cdrecord");
		if (p.getResult() != 0)
			throw new Exception("error running cdrecord -version");
		char str1[strlen(lineStr) + 1], str2[strlen(lineStr) + 1];
		if (sscanf(lineStr, "%s %s", str1, str2) != 2)
			throw new Exception("can't get version of cdrecord");
		char *str3 = new char[strlen(str1) + strlen(str2) + 2];
		sprintf(str3, "%s %s", str1, str2);
		cdrecordInfo = str3;
		log.put(lineStr);
	}

	private: void checkExecAsRoot(const char *fileName);

	private: void checkRawDevices() {
		for (int i = 0; i < numOfWriters; i++) {
			if (getActiveBoolean("simulation"))
				continue;

			if (!File(writerRawDevices[i]).exists())
				throw (new Exception(S.e
					+ "The raw device "
					+ writerRawDevices[i] + " does not exist!"));

			if (access(writerRawDevices[i], R_OK | W_OK) == -1) {
				throw (new Exception(S.e
					+ "Cannot read and write the raw device "
					+ writerRawDevices[i] + "!"))
				->addHelp(S.e + "Try\n"
					+ createHTMLTable(S.e
						+ "$ chown " + user + " " + writerRawDevices[i]
						+ "\n$ chmod u+rw" + " " + writerRawDevices[i]));
			}
		}
	}

	public: static String *createHTMLTable(String &str) {
		String *tab = new String(
			"<table bgcolor=#E0E0E0 cellpadding=10 width=100%>"
			"<tr><td><pre>");
		tab = &(*tab + str + "</pre></td></tr></table>");
		String::free(&str);
		return tab;
	}

	private: void evaluate(const char *str1, const char *str2);

	public: boolean getAccounts() {
		return accounts;
	}

	const char *getAccountsFile() {
		return accountsFile;
	}

	boolean getActiveBoolean(const char *key) {
		int index = indexOf(key);
		Object &object = items[index]->active;
		if (!object.instanceof("Boolean"))
			throw new Exception("invalid item in getActiveBoolean");
		Boolean *b = (Boolean *)&object;
		return b->booleanValue();
	}

	int getActiveInt(const char *key) {
		int index = indexOf(key);
		Object &object = items[index]->active;
		if (!object.instanceof("Integer"))
			throw new Exception("invalid item in getActiveInt");
		Integer *i = (Integer *)&object;
		return i->intValue();
	}

	String &getActiveValue(const char *key) {
		int index = indexOf(key);
		Object &object = items[index]->active;
		if (!object.instanceof("String"))
			throw new Exception("invalid item in getActiveValue");
		String *s = (String *)&object;
		return *s;
	}

	boolean getAnonymousUse() {
		return anonymousUse;
	}

	boolean getBurnProof() {
		return burnProof;
	}

	boolean getCdrdao() {
		return getActiveBoolean("cdrdao");
	}

	const char *getCdrdaoArgs() {
		return cdrdaoArgs;
	}

	const char *getCdrdaoPath() {
		return getActiveValue("cdrdaoPath").getBytes();
	}

	const char *getCdrecordArgs() {
		return cdrecordArgs;
	}

	const char *getCdrecordPath() {
		return getActiveValue("cdrecordPath").getBytes();
	}

	const char *getConfigDir() {
		return configDir;
	}

	boolean getCopySupport() {
		return copySupport && numOfReaders > 0;
	}

	const char *getDebug() {
		return debug;
	}

	const char *getDefaultFilesDir() {
		return defaultFilesDir;
	}

	int getDefaultSpeed() {
		return defaultSpeed;
	}

	int getDVDplusRWSupport(int writerNo) {
		return DVDplusRWSupport[writerNo];
	}

	boolean getEjectOnDone() {
		return ejectOnDone;
	}

	boolean getEjectOnReservation() {
		return ejectOnReservation;
	}

	const char *getEMailOnError() {
		return eMailOnError;
	}

	boolean getExportArchive() {
		return exportArchive;
	}

	const char *getFileName() {
		return fileName;
	}

	Exception *getFirstError() {
		return firstError;
	}

	const char *getFtpPubDir() {
		return ftpPubDir;
	}

	uid_t getGid() {
		return gid;
	}

	const char *getGroup() {
		return group;
	}

	const char *getHomeDir() {
		return homeDir;
	}

	const char *getImageFile(int writerNo) {
		return imageFile[writerNo];
	}

	boolean getImageOnTheFly() {
		return imageOnTheFly;
	}

	const char *getInfoFile() {
		return infoFile;
	}

	int getLaserOn() {
		return laserOn;
	}

	const char *getLogDir() {
		return logDir;
	}

	const char *getLogoURL() {
		return logoURL;
	}

	int getLogLevel() {
		return logLevel;
	}

	int getMaxCopies() {
		return maxCopies;
	}

	int getMaxMBytesInSpoolDir() {
		return maxMBytesInSpoolDir;
	}

	int getMaxMBytesPerSession() {
		return maxMBytesPerSession;
	}

	int getMaxOpenConnections() {
		return maxOpenConnections;
	}

	int getMaxOpenSessions() {
		return maxOpenSessions;
	}

	int getMaxSpeed() {
		return maxSpeed;
	}

	const char *getMkisofsArgs() {
		return mkisofsArgs;
	}

	const char *getMkisofsPath() {
		return getActiveValue("mkisofsPath").getBytes();
	}

	boolean getMP3decoding() {
		return MP3decoding;
	}

	private: String *getNameOfCopy(File &binary) {
		File binDir = new File(homeDir, "bin");
		File copy = new File(binDir, binary.getName());
		return new String(copy.getPath());
	}

	public: int getNumOfReaders() {
		return numOfReaders;
	}

	int getNumOfWriters() {
		return numOfWriters;
	}

	const char *getOrganization() {
		return organization;
	}

	unsigned short int getPortNo() {
		return getActiveInt("portNo");
	}

	private: const char *getRawDevice(
		int bus, int ID, int LUN, int no);

	public: const char *getReader(int no) {
		return CDROMs[no];
	}

	const char *getReaderInfo(int no) {
		return readerInfos[no];
	}

	const char *getReaderRawDevice(int no) {
		return readerRawDevices[no];
	}

	boolean getRemoveSessions() {
		return removeSessions;
	}

	int getReservedMBytes() {
		return reservedMBytes;
	}

	const char *getSetSchedulerPath() {
		return setSchedulerPath;
	}

	boolean getShowUsers() {
		return showUsers;
	}

	const char *getSpoolDir() {
		return spoolDir;
	}

	unsigned short int getStatusPortNo() {
		return statusPortNo;
	}

	uid_t getUid() {
		return uid;
	}

	const char *getUser() {
		return user;
	}

	boolean getVerify() {
		return verify;
	}

	const char *getVerifyPath() {
		return verifyPath;
	}

	int getWaitForCD() {
		return waitForCD;
	}

	const char *getWaitForCDMsgFile() {
		return waitForCDMsgFile;
	}

	const char *getWriter(int no) {
		return writers[no];
	}

	const char *getWriterInfo(int writerNo) {
		return writerInfos[writerNo];
	}

	const char *getWriterRawDevice(int writerNo) {
		return writerRawDevices[writerNo];
	}

	private: int indexOf(const char *key) {
		int index = search(key);
		if (index < 0)
			throw new Exception(S.e + key + " does not exist");
		return index;
	}

	public: int isDefault(const char *key) {
		int index = search(key);
		if (index < 0)
			throw new Exception(S.e + key + " does not exist");
		return items[index]->isDefault;
	}

	private: void parseCDROMs(
		const char *str, const char **list, int &count);

	public: static void parseLine(
		const char *lineStr, char *str1, char *str2);

	public: void prepareBinaries() {
		prepareBinary("cdrdaoPath");
		prepareBinary("cdrecordPath");
		prepareBinary("mkisofsPath");
	}

	private: void prepareBinary(const char *command) {
		String path = getActiveValue(command);
		File orig = new File(path);
		orig.complete();
		if (!orig.exists() || orig.isDirectory())
			return;

		String name = orig.getName();
		if (name.length() == 0)
			return;

		File copy = new File(getNameOfCopy(orig));
		copy.remove();
		copy.mkdirsParent();
		String cmd;
		cmd = cmd + "cp -p " + orig.getPath() + " " + copy.getPath();
		log.put(4, S.e + cmd.getBytes());
		system(cmd.getBytes());
		String cmd2;
		cmd2 = cmd2 + "chown root." + group + " " + copy.getPath();
		system(cmd2.getBytes());
		String cmd3;
		cmd3 = cmd3 + "chmod 4710" + " " + copy.getPath();
		system(cmd3.getBytes());
		File binDir = new File(homeDir, "bin");
		String cmd4;
		cmd4 = cmd4 + "chmod 755" + " " + binDir.getPath();
		system(cmd4.getBytes());

		log.put(2, S.e + "prepared " + command + " = " + copy.getPath());
	}

	private: void readConfigFile();

	public: void reload();

	private: int search(const char *key) {
		return search(key, 0, numOfItems - 1);
	}

	private: int search(const char *key, int a, int b) {
		if (a > b)
			return -1;

		int m = (a + b) / 2;
		int diff = items[m]->key.compareToIgnoreCase(key);
		if (diff > 0)
			return search(key, a, m - 1);
		else
			if (diff < 0)
				return search(key, m + 1, b);
			else
				return m;
	}

	private: void set(const char *key, boolean value) {
		int index = indexOf(key);
		*(Boolean *)&items[index]->active = new Boolean(value);
		items[index]->isConfig = false;
		items[index]->isDefault = false;
	}

	private: void set(const char *key, int value) {
		int index = indexOf(key);
		*(Integer *)&items[index]->active = new Integer(value);
		items[index]->isConfig = false;
		items[index]->isDefault = false;
	}

	private: void set(const char *key, const char *value) {
		int index = indexOf(key);
		*(String *)&items[index]->active = new String(value);
		items[index]->isConfig = false;
		items[index]->isDefault = false;
	}

	private: void setConfig(const char *key, const char *value) {
		int index = indexOf(key);
		if (items[index]->active.instanceof("Boolean"))
			set(key, Boolean::getBoolean(value));
		else
		if (items[index]->active.instanceof("Integer"))
			set(key, Integer::getInt(value));
		else
			set(key, value);
		items[index]->isConfig = true;
	}

	private: void setPathOfCopy(const char *command) {
		String str = getActiveValue(command);
		if (getActiveBoolean("simulation") && !str.endsWith("-dummy"))
			if (strcmp(command, "cdrdaoPath") != 0
					&& strcmp(command, "mkisofsPath") != 0)
				str = str + "-dummy";
		str = File(str).complete();
		File binary = File(str);
		String nameOfCopy = getNameOfCopy(binary);
		if (File(nameOfCopy).exists())
			str = nameOfCopy;
		checkExecAsRoot(str.getBytes());
		set(command, str.getBytes());
		log.put(2, S.e + command + " = " + str);
	}

	public: void setPermissions();

	private: void testMkisofs();
	private: void testMpg123();

	private: void Config::testOgg123() {
		Process ogg123(getActiveValue("ogg123Path"));
		ogg123.addArg("--version");
		ogg123.start();
		const char *lineStr = ogg123.readLine();
		if (lineStr == NULL)
			throw (new Exception(S.e + "Cannot run ogg123 ("
				+ getActiveValue("ogg123Path") + ")"))
				->addHelp(S.e + "Try one of\n<ul>\n"
					"<li>install the vorbis-tools"
						+ " and/or adjust <b>ogg123Path</b> in "
						+ fileName + "</li>\n"
					"<li>set <b>audioCDSupport=off</b> in "
						+ fileName + "</li></ul>");
		do {
			char str1[strlen(lineStr) + 1], str2[strlen(lineStr) + 1];
			if (sscanf(lineStr, "%s %[^:]", str1, str2) == 2)
				ogg123Info = str2;
			lineStr = ogg123.readLine();
		} while (lineStr != NULL);
	}

	private: void Config::testSox() {
		Process sox(getActiveValue("soxPath"));
		sox.addArg("-h");
		sox.start();
		const char *lineStr = sox.readLine();
		if (lineStr == NULL)
			throw (new Exception(S.e + "Cannot run sox ("
				+ getActiveValue("soxPath") + ")"))
				->addHelp(S.e + "Try one of\n<ul>\n"
					"<li>install sox and/or adjust <b>soxPath</b> in "
						+ fileName + "</li>\n"
					"<li>set <b>audioCDSupport=off</b> in "
						+ fileName + "</li></ul>");
		do {
			char str1[strlen(lineStr) + 1], str2[strlen(lineStr) + 1];
			if (sscanf(lineStr, "%[^:]: Version %s", str1, str2) == 2)
				soxInfo = str2;
			lineStr = sox.readLine();
		} while (lineStr != NULL);
	}

	static gid_t toGid(const char *groupName);
	static const char *toGroup(gid_t gid);
	public: String &toHTML();
	private: static const char *toString(boolean b);
	static uid_t toUid(const char *userName);
	static const char *toUser(uid_t uid);
	void write();
	void write(const char *str);
	void write(const char *str1, const char *str2);
	void write(const char *str, int number);
	void writeConfigFile();
	void writeInfoFile();
	void writeWaitForCDMsgFile();
};

extern Config config;

#endif
