/***************************************************************************
 *   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 "messagebox.h"
#include <kapplication.h>
#include <kuniqueapplication.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.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>

static const char description[] =
    I18N_NOOP("이 프로그램은 KDE3용 리눅스 네이트온 메신저를 위한 통합메시지함 입니다.");

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

	KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( options );
#if 0
  KUniqueApplication::addCmdLineOptions();
  /*!
   * 하나만 실행되도록 하는 클래스
   * 수정 필요~
   */
  if ( !KUniqueApplication::start() )
  {
    fprintf(stderr, "messagebox 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, "messagebox is already running!\n");
    exit(0);
  }
#endif
  // KUniqueApplication app;
  KApplication app;
    messagebox *mainWin = 0;

    if (app.isRestored())
    {
        RESTORE(messagebox);
    }
    else
    {
        // no session.. just start up normally
        KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

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

        mainWin = new messagebox();
        app.setMainWidget( mainWin );
        mainWin->show();
        // app.setName("xxx");
        args->clear();
    }

    // mainWin has WDestructiveClose flag by default, so it will delete itself.
    app.exec();
  
  return 0;
}

