/***************************************************************************
 *   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)
{
	// signal(SIGPIPE,SIG_IGN);
	/*!
	  KAboutData about("kwalletmanager", I18N_NOOP("KDE Wallet Manager"), "1.1",
	  I18N_NOOP("KDE Wallet Management Tool"),
	  KAboutData::License_GPL,
	  I18N_NOOP("(c) 2003,2004 George Staikos"), 0,
	  "http://www.kde.org/");
	*/
	memset(version, 0x00, 1000);
	snprintf( version, 1000, "%d.%d.%d.%d Beta", NATEON_VER_MAJOR, NATEON_VER_MINOR, NATEON_VER_PATCH, NATEON_VER_RELEASE );
	
	KAboutData aboutData("nateon", I18N_NOOP("네이트온 메신저"),
	                     version,
						 description,
	                     KAboutData::License_Custom,
	                     I18N_NOOP("(C) 2007 SK Communications, Inc."), 0, "http://nateonweb.nate.com");
	/*!
	개발자 정보
	*/
	aboutData.addAuthor( I18N_NOOP("장두현"), I18N_NOOP("프로젝트 관리자"), "dh.jang@gmail.com", "http://kldp.net/projects/nateon/" );
	aboutData.addAuthor( I18N_NOOP("SeongOok Choi"), I18N_NOOP("개발자"), "kakapapa@nate.com" );
	aboutData.addAuthor( I18N_NOOP("YoungHo Park"), I18N_NOOP("개발자"), "amesianx@nate.com" );
	aboutData.addAuthor( I18N_NOOP("Park \"segfault\" Joon-Kyu"), I18N_NOOP("개발자"), "mastermind@planetmono.org", "http://planetmono.org" );
	aboutData.addAuthor( I18N_NOOP("korone"), I18N_NOOP("개발자"), "korone@gmail.com", "http://korone.net" );
	aboutData.addAuthor( I18N_NOOP("태훈"), I18N_NOOP("개발자"), "kth3321@gmail.com", "http://onestep.tistory.com/" );
	aboutData.addAuthor( I18N_NOOP("Byoungyoung La"), I18N_NOOP("개발자"), "la9527@yahoo.co.kr" );
	aboutData.addAuthor( I18N_NOOP("Dong-hee Na(acsungcode)"), I18N_NOOP("개발자"), "corona10@gmail.com", "http://acsungcode.tistory.com/" );
	aboutData.addAuthor( I18N_NOOP("Jun S. Kang (zingle)"), I18N_NOOP("개발자"), "zingle@gmail.com" );
	aboutData.addAuthor( I18N_NOOP("임인택 (litnsio2)"), I18N_NOOP("개발자"), "masterhand@gmail.com" );
	aboutData.addAuthor( I18N_NOOP("김동진"), I18N_NOOP("개발자"), "tobetter@gmail.com" );
	aboutData.addAuthor( I18N_NOOP("신홍중 (whitepoo)"), I18N_NOOP("개발자"), "sjtetris@daum.net" );
	aboutData.addAuthor( I18N_NOOP("정재훈 (dicastyle)"), I18N_NOOP("개발자"), "dicastyle@nate.com" );
	aboutData.addAuthor( I18N_NOOP("조병탁 (jbtstyle)"), I18N_NOOP("개발자"), "jbtstyle@gmail.com" );
	aboutData.addAuthor( I18N_NOOP("전창현 (expectedtime)"), I18N_NOOP("개발자"), "cch870906@gmail.com" );
	aboutData.addAuthor( I18N_NOOP("노연진 (nyjin)"), I18N_NOOP("개발자"), "zacronan@naver.com" );
	aboutData.addAuthor( I18N_NOOP("유경진 (kyoji)"), I18N_NOOP("개발자"), "yookyoji@hotmail.com" );
	aboutData.addAuthor( I18N_NOOP("최수현 (soohyunc)"), I18N_NOOP("개발자"), "s.choi@hackers.org.uk", "http://www.cs.ucl.ac.uk/staff/S.Choi" );
	aboutData.addAuthor( I18N_NOOP("이지석 (morgana)"), I18N_NOOP("개발자"), "morgana@naver.com" );
	
	/*!
	도움주신 분
	*/
	aboutData.addCredit( I18N_NOOP("이은아"), I18N_NOOP("리눅스 네이트온 기획"), "ena27@nate.com" );
	aboutData.addCredit( I18N_NOOP("이승명"), I18N_NOOP("디자이너"), "smdesign@nate.com", "http://www.leesm.com" );
	aboutData.addCredit( I18N_NOOP("박상완"), I18N_NOOP("버그트래킹서버 제공, 버그 수정"), "nakyup@gmail.com", "http://people.sarang.net" );
	aboutData.addCredit( I18N_NOOP("강정희"), I18N_NOOP("automake 부분"), "keizie@gmail.com" );
	aboutData.addCredit( I18N_NOOP("김가현"), I18N_NOOP("설치 도움"), "kfmes@kfmes.com", "http://kfmes.com" );
	aboutData.addCredit( I18N_NOOP("A Lee"), I18N_NOOP("Debian 패키징"), "alee@debian.org" );
	aboutData.addCredit( I18N_NOOP("Hyunsik Choi"), I18N_NOOP("Gentoo 패키징"), "c0d3h4ck@gmail.com" );
	aboutData.addCredit( I18N_NOOP("Barosl LEE"), I18N_NOOP("(k)ubuntu 패키징"), "", "http://barosl.com" );
	aboutData.addCredit( I18N_NOOP("Hwang YunSong"), I18N_NOOP("Asianux 패키징"), "hys545@dreamwiz.com" );
	aboutData.addCredit( I18N_NOOP("시노 삐 (sinovino)"), I18N_NOOP("(k)ubuntu 패키징"), "sinovino@sinovino.org" );
	aboutData.addCredit( I18N_NOOP("Sang-Kyun Noh"), I18N_NOOP("아치리눅스(Arch Linux) 패키징"), "freesky80@nate.com" );
	aboutData.addCredit( I18N_NOOP("정하영(sixt06)"), I18N_NOOP("openSUSE 패키징"), "sixt06@gmail.com" );
	aboutData.addCredit( I18N_NOOP("이상현(sanghyun)"), I18N_NOOP("Fedoa 패키징"), "SangHyun.0925@gmail.com" );
	
	KCmdLineArgs::init(argc, argv, &aboutData);
	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;
}

