/* Copyright 2021 m-privacy GmbH.
 *
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
 * USA.
 */

#include <pwd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#if !defined(WIN32) && !defined(WIN64)
#include <syslog.h>
#endif

#include <rfb/LogWriter.h>
#include <rfb/ServerCore.h>
#include <rfb/SSecurityMulti.h>

#include "SAutotransferNow.h"

static rfb::LogWriter vlog("SAutotransferNow");

SAutotransferNow::SAutotransferNow(rfb::SSecurityMulti* multi): SAutotransferDirWatcher()
{
	this->multi = multi;

	// Send autotransferClientDir set with the config menu
	const char* autotransferClientDir = rfb::Server::autotransferClientDir.getData();
	if (autotransferClientDir && *autotransferClientDir) {
		vlog.debug("%s: Sending signal with autotransferFolder to client: %s", __func__, autotransferClientDir);
		multi->sendSignal(AUTOTRANSFERPATH_SIGNAL_ID, autotransferClientDir, strlen(autotransferClientDir) + 1);
	} else {
		vlog.debug("%s: autotransferClientDir. The client will be able to decide where to auto-download stuff.", __func__);
	}
}

std::string SAutotransferNow::getWatcherName() const {
	return "SAutotransferNow";
}

std::string SAutotransferNow::getDirToWatch() const
{
	return "/home/user/.autotransfer-now/" + getEffectiveUser();
}

void SAutotransferNow::processFile(char* filename)
{
	vlog.debug("%s: Sending file '%s' through multi", __func__, filename);
	multi->sendFile(filename, FILE_TRANSFER_STREAM_ID, AUTOTRANSFER_PROTOCOL_V1, true);
}
