/* thumbsync.cpp
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Console application for synchronizing two directories.
*/

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <sstream>
#include <stdexcept>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <fts.h>

using std::cout;
using std::cin;
using std::strcoll;
using std::string;
using std::vector;
using std::runtime_error;
using std::endl;
using std::ostringstream;
using std::ostream;
using std::system;



int alphabetize(const FTSENT **a, const FTSENT **b)
{
	return strcoll((*a)->fts_name, (*b)->fts_name);
}



class FileRecord {
public:
	// FileRecords will be constructed inside a vector.
	// To avoid copying extra data, call SetData() on the record in the vector
	// after it has been allocated, instead of allocating then copying the string.
	void SetData(const FTSENT &ent)
	{
		depthChange = (ent.fts_info == FTS_D) - (ent.fts_info == FTS_DP);
		
		if(ent.fts_level)
		{
			name.assign(ent.fts_name, ent.fts_namelen);
			if(ent.fts_info == FTS_SL)
				timestamp = 0;
			else
				// FAT file system only stores time in multiples of 2 seconds.
				timestamp = ent.fts_statp->st_mtimespec.tv_sec & ~1;
		}
	}
	
	int Compare(const FileRecord &record) const
	{
		int endpoint = (depthChange == -1) - (record.depthChange == -1);
		
		if(!endpoint)
			return strcoll(name.c_str(), record.name.c_str());
			
		return endpoint;
	}
	
	string name;
	time_t timestamp;
	char depthChange;
};



void ReadDirectory(string path, vector<FileRecord> &files)
{
	char *paths[2] = {const_cast<char *>(path.c_str()), NULL};
	FTS *fts = fts_open(paths, FTS_PHYSICAL, &alphabetize);
	
	if(!fts)
		throw runtime_error("Unable to open directory.");

	FTSENT *ent;
	
	while(ent = fts_read(fts))
	{
		string name(ent->fts_name, ent->fts_namelen);
		if(name[0] == '.')
			continue;
		
		if(name == "build")
		{
			fts_set(fts, ent, FTS_SKIP);
			continue;
		}
		
		files.push_back(FileRecord());
		files.back().SetData(*ent);
	}
		
	fts_close(fts);
}



int main(int argc, char *argv[])
{
	string root[2];
	
	int pathCount = 0;
	bool doConfirm = true;
	for(int i = 1; i < argc; ++i)
	{
		if(argv[i][0] != '-')
		{
			if(pathCount >= 2)
			{
				cout<<"Only two paths may be specified."<<endl;
				return 0;
			}
			root[pathCount] = argv[i];
			++pathCount;
		}
		else
		{
			// Options: -f for no confirmation, -i for confirmation (default).
			if(argv[i][1] == 'f')
				doConfirm = false;
			else if(argv[i][1] == 'i')
				doConfirm = true;
			else
			{
				cout<<"Option "<<argv[i]<<" not recognized."<<endl;
				return 0;
			}
		}
	}
	
	if(pathCount < 2)
	{
		cout<<"Please specify two directories to synchronize."<<endl;
		return 0;
	}
	
	for(int i = 0; i < 2; ++i)
		if(root[i][root[i].length() - 1] == '/')
			root[i].erase(root[i].length() - 1);
	
	vector<FileRecord> aFiles;
	vector<FileRecord> bFiles;
	
	ReadDirectory(root[0], aFiles);
	ReadDirectory(root[1], bFiles);
	
	vector<FileRecord>::const_iterator aIt = aFiles.begin();
	vector<FileRecord>::const_iterator bIt = bFiles.begin();
	
	string path;
	vector<size_t> lengthStack;
	
	vector<string> commands;
	
	while(true)
	{
		int compare = aIt->Compare(*bIt);
		int copyDirection = compare;
		
		if(!copyDirection)
		{
			if(!aIt->depthChange)
				copyDirection = (aIt->timestamp < bIt->timestamp) - (aIt->timestamp > bIt->timestamp);
			else if(aIt->depthChange > 0)
			{
				lengthStack.push_back(path.size());
				path += aIt->name + "/";
			}
			else
			{
				path.erase(lengthStack.back());
				lengthStack.pop_back();
				if(lengthStack.empty())
					break;
			}
		}
		
		if(copyDirection != 0)
		{
			string aPath = root[0] + path;
			string bPath = root[1] + path;
			
			if(copyDirection < 0)
				commands.push_back("cp -Rfp \"" + aPath + aIt->name + "\" \\\n    \"" + bPath + "\"");
			else
				commands.push_back("cp -Rfp \"" + bPath + bIt->name + "\" \\\n    \"" + aPath + "\"");
		}
		
		if(compare < 0)
			for(int depth = 0; depth += (aIt++)->depthChange; ) {}
		else if(compare > 0)
			for(int depth = 0; depth += (bIt++)->depthChange; ) {}
		else
		{
			++aIt;
			++bIt;
		}
	}
	
	if(commands.empty())
	{
		cout<<"The two locations are identical."<<endl;
		return 0;
	}
	
	if(doConfirm)
	{
		cout<<"I am going to execute the following commands: "<<endl;
		for(vector<string>::const_iterator cIt = commands.begin(); cIt != commands.end(); ++cIt)
			cout<<*cIt<<endl;
		cout<<"Continue? (y/n) [n]: ";
		char response = cin.get();
		if(response != 'y' && response != 'Y')
			return 0;
	}
	
	for(vector<string>::const_iterator cIt = commands.begin(); cIt != commands.end(); ++cIt)
		system(cIt->c_str());
	
	return 0;
}



/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */

