#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# create cmake build system files by iterating all available languages [1]
# 

import os
import sys

global dirs
dirs = {}

def treewalker(directory, callback, includetype=[],excludetype=[]):
    join = os.path.join
    dirs[directory]=[] #takes care of top directory
    for f in os.listdir(directory):
        pathname = join(directory, f)
        if os.path.isdir(pathname) and pathname.find(".svn") == -1:
            # TODO apply exclude filter
            dirs[pathname] = [] #add key
            #print "...in %s" % (pathname)
            treewalker(pathname, callback, includetype,excludetype)
        elif os.path.isfile(pathname) :
            callback(pathname, includetype,excludetype)

def callback(pathname, includetype=[],excludetype=[]):

    dirname = os.path.dirname(pathname)
    ext = os.path.splitext(pathname)[1]
    if len(includetype) > 0: 
        for _ext in includetype:
            if len(ext) > 0 and _ext == ext:
                dirs[dirname].append(os.path.normpath(pathname))
    if len(excludetype) > 0: 
        for _ext in excludetype:
            if len(ext) > 0 and _ext <> ext:
                dirs[dirname].append(os.path.normpath(pathname))


def createTopLevelCMakeListFile(langdir):
    topLevelCmakeList = os.path.join(langdir,'CMakeLists.txt')
    if not os.path.exists(topLevelCmakeList):
        content = "                                            \n\
project(kde-i18n-%s)                                           \n\
                                                               \n\
# Search KDE installation                                      \n\
find_package(KDE4 REQUIRED)                                    \n\
find_package(Gettext REQUIRED)                                 \n\
include (KDE4Defaults)                                         \n\
include(MacroOptionalAddSubdirectory)                          \n\
                                                               \n\
if (NOT GETTEXT_MSGMERGE_EXECUTABLE)                           \n\
   MESSAGE(FATAL_ERROR \"Please install the msgmerge binary\") \n\
endif (NOT GETTEXT_MSGMERGE_EXECUTABLE)                        \n\
                                                               \n\
IF(NOT GETTEXT_MSGFMT_EXECUTABLE)                              \n\
   MESSAGE(FATAL_ERROR \"Please install the msgfmt binary\")   \n\
endif (NOT GETTEXT_MSGFMT_EXECUTABLE)                          \n\
" % (langdir)
        f = open(topLevelCmakeList,"w")
        f.write(content)

        f.write('set(CURRENT_LANG %s)\n\n' % (langdir))
        return f

# handle UI message catalogs.
# write into top level makefile
def add_cmake_files_messages_toplevel(langdir,f):
    dir = os.path.join(langdir,'messages')
    if not os.path.exists(docs):
        return
    suffix = [".po"]
    treewalker(dir, callback, suffix)
    f.write("set (MESSAGES_PO_FILES\n")
    for dir in dirs.keys():
        l = dirs[dir]
        if len(l)>0:
            for file in l:            
                fi = file.replace(langdir+"\\","").replace("\\","/")
                f.write("    %s\n" % (fi))
    f.write(")\n")
    f.write("GETTEXT_PROCESS_PO_FILES(${CURRENT_LANG} ALL INSTALL_DESTINATION ${LOCALE_INSTALL_DIR} ${MESSAGES_PO_FILES} )\n")
    f.write("install(FILES ${MESSAGES_PO_FILES} DESTINATION ${LOCALE_INSTALL_DIR}/${CURRENT_LANG}/ )\n")

# handle UI message catalogs.
# write targets into messages/CMakeLists.txt 
def add_cmake_files_messages(langdir,f):
    dir = os.path.join(langdir,'messages')
    if not os.path.exists(docs):
        return
    f.write("add_subdirectory( messages )\n")

    filename = os.path.join(dir,"CMakeLists.txt")
    fc = open(filename, "w")
    suffix = [".po"]
    treewalker(dir, callback, suffix)
    fc.write("set (MESSAGES_PO_FILES\n")
    for dir in dirs.keys():
    	# TODO exclude 'dirs=`cd $dir/messages && find * -maxdepth 1 -type d | fgrep -v others | fgrep -v www.kde.org | fgrep -v .svn`'
        l = dirs[dir]
        if len(l)>0:
            for file in l:            
                fi = file.replace(langdir+"\\","").replace("\\","/")
                fc.write("    %s\n" % (fi))
    fc.write(")\n")
    fc.write("GETTEXT_PROCESS_PO_FILES(${CURRENT_LANG} ALL INSTALL_DESTINATION ${LOCALE_INSTALL_DIR} ${MESSAGES_PO_FILES} )\n")
    fc.write("install(FILES ${MESSAGES_PO_FILES} DESTINATION ${LOCALE_INSTALL_DIR}/${CURRENT_LANG}/ )\n")
    fc.close

# handle UI doc message catalog.
def add_cmake_files_docmessages(langdir,f):
    dir = os.path.join(langdir,'docmessages')
    if not os.path.exists(dir):
        return
    suffix = [".po"]
    treewalker(dir, callback, suffix)
    f.write("set (DOCMESSAGES_PO_FILES\n")
    for dir in dirs.keys():
        l = dirs[dir]
        if len(l)>0:
            for file in l:            
                fi = file.replace(langdir+"\\","").replace("\\","/")
                f.write("    %s\n" % (fi))
    f.write(")\n")
    f.write("GETTEXT_PROCESS_PO_FILES(${CURRENT_LANG} ALL INSTALL_DESTINATION ${LOCALE_INSTALL_DIR} ${DOCMESSAGES_PO_FILES} )\n")
    f.write("install(FILES ${DOCMESSAGES_PO_FILES} DESTINATION ${LOCALE_INSTALL_DIR}/${CURRENT_LANG}/ )\n")


def add_cmake_files_docs(langdir,f):
    docs = os.path.join(langdir,'docs')
    if not os.path.exists(docs):
        return
    excludesuffix = [".svn",".svn-base"]
    treewalker(docs, callback, [], excludesuffix)
    files = []
    for dir in dirs.keys():
        l = dirs[dir]
        if len(l)>0:
            for file in l:            
                fi = file.replace(langdir+"\\","").replace("\\","/")
                ext = os.path.splitext(fi)[1]
                print fi + " " + ext
                if ext == ".docbook":
                    f.write("kde4_create_handbook(%s INSTALL_DESTINATION ${HTML_INSTALL_DIR}/${CURRENT_LANG}/  )\n" % (fi))
                else: 
                    if ext == ".png" or ext == ".css" or ext == ".html":
                        files.append(fi)
                                                  
    f.write("set (FILES\n")
    
    for file in files:
        f.write("    %s\n" % (file))
    f.write(")\n")
        
#    f.write("install( FILES ${FILES} DESTINATION ${HTML_INSTALL_DIR}/${CURRENT_LANG}/common)" >> $dir_local/$subdir/CMakeLists.txt;
                    
#    # This is just not to make a find * in a dir that has no items and so we avoid getting a find warning
#    count=`cd $dir_local && find . -mindepth 1 -maxdepth 1 -regex '.*' | egrep -v .svn | wc -l`
#    if [ $count -eq 0 ]; then
#          return
#    fi
#      list_dir=`cd $dir_local && find * -maxdepth 0 -type d | egrep -v .svn`;
#      # remove old CMakeLists.txt
#      rm -f $dir_local/CMakeLists.txt;
#      for subdir in $list_dir; do
#          echo "add_subdirectory( $subdir )" >> $dir_local/CMakeLists.txt
#          add_cmake_files_doc $dir_local/$subdir;
#          case $subdir in
#               common)
#                   echo "FILE(GLOB _html *.html)" >> $dir_local/$subdir/CMakeLists.txt;
#                   echo "FILE(GLOB _css *.css)" >> $dir_local/$subdir/CMakeLists.txt;
#                   echo "FILE(GLOB _pngs *.png)" >> $dir_local/$subdir/CMakeLists.txt;
#                   echo "install( FILES \${_html} \${_css} \${_png} DESTINATION \${HTML_INSTALL_DIR}/\${CURRENT_LANG}/common)" >> $dir_local/$subdir/CMakeLists.txt;
#                   #howto install the missing symlinks e.g. ${HTML_INSTALL_DIR}/en/common/1.png  ${HTML_INSTALL_DIR}/\${CURRENT_LANG}/common/1.png ?
#                   ;;
#               *)
#                   if test -f $dir_local/$subdir/index.docbook; then
#                       # test if it's a kcontrol module.
#                       local kcontrol_found=`echo $dir_local/$subdir | grep kcontrol`;
#                       local add_subdir=;
#                       if [  ! -z $kcontrol_found ]; then
#                            add_subdir="SUBDIR kcontrol/$subdir";
#                       fi
#                       # test if it's a kinfocenter module.
#                       local kinfocenter_found=`echo $dir_local/$subdir | grep kinfocenter`;
#                       if [  ! -z $kinfocenter_found ]; then 
#                            add_subdir="SUBDIR kinfocenter/$subdir";  
#                       fi
#                       # test if it's a khelpcenter module (faq, glossary quickstart userguide visualdict
#                       local faq_found=`echo $dir_local/$subdir | grep faq`;
#                       if [  ! -z $faq_found ]; then 
#                            add_subdir="SUBDIR khelpcenter/$subdir";
#                       fi
#                       local glossary_found=`echo $dir_local/$subdir | grep glossary`;
#                       if [  ! -z $glossary_found ]; then 
#                            add_subdir="SUBDIR khelpcenter/$subdir";
#                       fi
#                       local quickstart_found=`echo $dir_local/$subdir | grep quickstart`;
#                       if [  ! -z $quickstart_found ]; then 
#                            add_subdir="SUBDIR khelpcenter/$subdir";
#                       fi
#                       local userguide_found=`echo $dir_local/$subdir | grep userguide`;
#                       if [  ! -z $userguide_found ]; then 
#                            add_subdir="SUBDIR khelpcenter/$subdir";
#                       fi
#                       local visualdict_found=`echo $dir_local/$subdir | grep visualdict`;
#                       if [  ! -z $visualdict_found ]; then 
#                            add_subdir="SUBDIR khelpcenter/$subdir";
#                       fi
#                       echo "kde4_create_handbook(index.docbook INSTALL_DESTINATION \${HTML_INSTALL_DIR}/\${CURRENT_LANG}/ $add_subdir )" >> $dir_local/$subdir/CMakeLists.txt;
#                   fi
#                   ;;
#          esac
#      done
#    }
#
#

subdirs = sys.argv[1:]
print subdirs

if not subdirs:
    fileName = 'inst-apps'
    if not os.path.exists(fileName):
        fileName = 'subdirs'
    f = open(fileName, "r" )
    for line in f.read().splitlines():
        subdirs.append(line)
    f.close()

# Go through all subdirs
for langdir in subdirs:
    print "processing %s" % (langdir)
    f = createTopLevelCmakeListFile(langdir)

    add_cmake_files_messages(langdir,f)

    add_cmake_files_docmessages(langdir,f)

    # Custom localized application data.
    add_cmake_files_data(langdir,f)

    # docs .
    add_cmake_files_docs(langdir,f)

    f.close()
