// sudo ./uncompress_stardict_dic /home/huzheng/stardict-dic/

// Then look at /usr/share/stardict/dic/

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

#include <glib.h>

void uncompress_dic(const char *fullfilename, const char *fullfiledir)
{
	if (g_str_has_suffix(fullfilename, "index.html") || g_str_has_suffix(fullfilename, "ads.txt") || g_str_has_suffix(fullfilename, "readme.txt") || g_str_has_suffix(fullfilename, "QQWry.Dat.bz2") || g_str_has_suffix(fullfilename, "stardict-treedict-gKamus-English-2.4.2.tar.bz2") || g_str_has_suffix(fullfilename, "stardict-treedict-gKamus-English-2.4.2.tar.bz2") || g_str_has_suffix(fullfilename, "stardict-treedict-infoBrowse-zh_CN-2.4.2.tar.bz2")) {
		return;
	}
	char command[512];
	sprintf(command, "tar -xaf %s -C %s", fullfilename, fullfiledir);
	int result;
	result = system(command);
	if (result == -1) {
		g_print("system() error!\n");
	}
}

void uncompress_stardict_dic(const char *dirname, int len)
{
	GDir *dir = g_dir_open(dirname, 0, NULL);
	if (!dir) {
		g_print("Open %s failed!", dirname);
		return;
	}
	const gchar *filename;
	gchar fullfiledir[512];
	gchar fullfilename[512];
	char command[512];
	while ((filename = g_dir_read_name(dir))!=NULL) {
	        sprintf(fullfilename, "%s%s", dirname, filename);
		if (g_file_test(fullfilename, G_FILE_TEST_IS_DIR)) {
                	sprintf(command, "mkdir /usr/share/stardict/dic/%s/%s", dirname+len, filename);
                	system(command);
			sprintf(fullfiledir, "%s%s/", dirname, filename);
			uncompress_stardict_dic(fullfiledir, len);
		} else {
		        sprintf(fullfiledir, "/usr/share/stardict/dic/%s", dirname+len);
			uncompress_dic(fullfilename, fullfiledir);
		}
	}
	g_dir_close(dir);
}

int main(int argc,char * argv [])
{
	if (geteuid() != 0) {
		g_print("Need to run as root! Try sudo!\n");
		return TRUE;
	}
	if (argc!=2) {
		g_print("Try \"sudo ./uncompress_stardict_dic /home/huzheng/stardict-dic/\" !\n");
		return TRUE;
	}
	int base_len;
	base_len = strlen(argv[1]);
	if (argv[1][base_len-1] != '/') {
		g_print("The last character need to be '/', such as \"/home/huzheng/stardict-dic/\"\n");
		return TRUE;
	}
	system("mkdir -p /usr/share/stardict/dic/");
	uncompress_stardict_dic(argv[1], base_len);
	return FALSE;
}

