/***************************************************************************
 *   Copyright (C) 2008 by SK Communications.                              *
 *   http://kldp.net/projects/nateon/                                      *
 *                                                                         *
 *   This program 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 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "version.h"
#include "knateon.h"
#include <kapplication.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.h>
#include <qlayout.h>
#include <qfile.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <errno.h>
#include <fcntl.h>
#include <kuniqueapplication.h>
#include <signal.h>
#include "util/common.h"
#include "util/emoticon.h"

static const char description[] = I18N_NOOP("이것은 KDE3용 네이트온 메신저 입니다.");

// static const char version[] = VERSION; // "1.0 beta";

static KCmdLineOptions options[] =
{
    //    { "+[URL]", I18N_NOOP( "Document to open" ), 0 },
    KCmdLineLastOption
};

bool GrabPIDLock()
{
	// open the PID file in the users ktorrent directory and attempt to lock it
	QString pid_file = QDir::homeDirPath() + "/.knateon.lock";
  
	int fd = open(QFile::encodeName(pid_file),O_RDWR|O_CREAT,0640);
	if (fd < 0)
	{
		fprintf(stderr,"Failed to open KT lock file %s : %s\n",pid_file.ascii(),strerror(errno));
		return false;
	}
  
	if (lockf(fd,F_TLOCK,0)<0)
	{
		fprintf(stderr,"Failed to get lock on %s : %s\n",pid_file.ascii(),strerror(errno));
		return false;
	}
  
	char str[20];
	sprintf(str,"%d\n",getpid());
	write(fd,str,strlen(str)); /* record pid to lockfile */
  
	// leave file open, so nobody else can lock it until KT exists
	return true;
}

static char version[1000];

int main(int argc, char **argv)
{
	KCmdLineArgs::init(argc, argv, LNMUtils::getAboutData("이것은 KDE3용 네이트온 메신저 입니다.") );
	KCmdLineArgs::addCmdLineOptions( options );
#if 0
	KUniqueApplication::addCmdLineOptions();
	/*!
	 * 하나만 실행되도록 하는 클래스
	 * 수정 필요~
	 */
	if ( !KUniqueApplication::start() )
	{
		fprintf(stderr, "knateon is already running!\n");
		exit(0);
	}
#endif
#if 1
	// need to grab lock after the fork call in start, otherwise this will not work properly
	if ( !GrabPIDLock() )
	{
		fprintf(stderr, "knateon is already running!\n");
		exit(0);
	}
#endif
  
  
#if 0
	try
	{
#endif
		// KUniqueApplication app;
		KApplication app;
		// KNateon *pMainWindow = 0;

  
		// no session.. just start up normally
		KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

		/// @todo do something with the command line args here

		/*!
		 * KVpnc *kvpnc = new KVpnc( &a );
		 * a.setMainWidget( kvpnc );
		 */
  
		KNateon *pMainWindow = new KNateon( &app /* ,"MainWindow" */);

		if (pMainWindow && pMainWindow->initialize())
		{
			//  pMainWindow->setStandardToolBarMenuEnabled(true);
			// pMainWindow.resize( 400, 400 );
			// pMainWindow.setCaption( "KNateon - Nateon Messenger for KDE" );
			// pMainWindow.setAllColumnsShowFocus( TRUE );
			app.setMainWidget( pMainWindow );
			pMainWindow->show();
		}

		args->clear();

		// mainWin has WDestructiveClose flag by default, so it will delete itself.
		app.exec();
#if 0
	}
	catch (bt::Error & e)
	{
		fprintf(stderr, "Aborted by error : %s\n",e.toString().ascii());
	}
#endif
	//  Globals::cleanup();
  
//  printf("\n\nObjects alive = %i\n\n",(unsigned int)Object::numAlive());
	return 0;
}

