# Loading required libraries
import os
import sys
import glob
import commands


# First of all let's see if the user needs help
Help("""
Welcome to the Klostein Stereoscope installation script
-------------------------------------------------------

$ scons -h
gives this screen

$ scons
will build the project

$ scons install
installs the plugin

$ scons uninstall
removes it again

and $ scons clean
will keep our project directory clean


Please have a look at the file 'version' if you plan to install several
(slightly modified) instances of the same plugin.


The Klostein Stereoscope is Free Software. Its actual license is any
version of the GNU GPL from version 2 on.

Please send your comments and bug reports to dennis -at- windows3.de

Enjoy!
""")

if not '-h' in sys.argv:


   print("")


   # Then of all let's check for silly command line arguments
   if 'install' in COMMAND_LINE_TARGETS and 'uninstall' in COMMAND_LINE_TARGETS:
      print('Why should you want to install and uninstall at the same time?')
      Exit(1)

   if  not COMMAND_LINE_TARGETS == [] \
   and not 'install'   in COMMAND_LINE_TARGETS \
   and not 'uninstall' in COMMAND_LINE_TARGETS \
   and not 'clean'     in COMMAND_LINE_TARGETS:
      print('Please issue\n   $ scons -h\n   $ scons\n   $ scons install\n   $ scons uninstall\nor $ scons clean\n')
      Exit(1)


   # Defining some command line options for later use
   opts = Options('version')
   opts.Add('VERSION', 'Adds an sufix to the plugin name. Handy for installing several versions.', '0.00')


   # Setting up a buld environment with all env. variables from the console
   usedlibs = ""

   env = Environment(ENV = os.environ,
#                     CCFLAGS = "-g -Wall `pkg-config --cflags " + usedlibs + "` `xmms-config --cflags`",
#                     LINKFLAGS = "-g -Wall -export-dynamic `pkg-config --libs " + usedlibs + "` `xmms-config --libs`",
                     CCFLAGS = "-g -Wall `xmms-config --cflags`",
                     LINKFLAGS = "-g -Wall -export-dynamic `xmms-config --libs`",
                     options = opts)
   Help(opts.GenerateHelpText(env))

   BuildDir('bin', 'src', 0)
   build_dir = 'bin/'
   conf_header = 'src/config.h'
   inst_dir = ''
   plug_dir_cache = '.plugdir'
   libname = 'xmmss-' + str(env['VERSION'])
   libname = os.path.join(build_dir, libname)


   # No tests needed if the user requests cleaning
   if 'clean' in COMMAND_LINE_TARGETS:
      if os.access(conf_header, os.F_OK):
         os.remove(conf_header)

      SetOption('clean', 1)
      env.Alias('clean', build_dir)

   else:

      # Looking if xmms is installed
      print('Looking for xmms')
      if not os.system('xmms -v') == 0:
         print("Couldn't find xmms.")
         Exit(1)

      print("")


      # Trying xmms-config
      print("Trying xmms-config")
      if not commands.getoutput('xmms-config --version'):
         print("Couldn't run xmms-config.")
         print("If you didn't compile xmms yourself your might consider doing so.")
         Exit(1)

      print("Reading xmms configuration")
      inst_dir = commands.getoutput('xmms-config --visualization-plugin-dir')
      if not os.access(inst_dir,os.F_OK):
         print("Couldn't determine the plugin directory.")
         print("Please see that xmms and xmms-config are installed properly.")
         Exit(1)


      print(inst_dir)
      print("")

      sub_dir_name = 'libxmmss-' + str(env['VERSION'])
      inst_dir1 = os.path.join(inst_dir, sub_dir_name)


      # We can't compile without pkg-config
      print('Looking for pkg-config')
      if not os.system('pkg-config --version') == 0:
         print("pkg-config is needed for successful compilation.")
         Exit(1)

      print("")


      # Checking for needed libraries
      conf = Configure(env)

      if not conf.CheckCHeader('stdio.h'):
         Exit(1)

      if not conf.CheckCHeader('stdlib.h'):
         Exit(1)

      if not conf.CheckCHeader('stddef.h'):
         Exit(1)

      if not conf.CheckCHeader('string.h'):
         Exit(1)

      if not conf.CheckCHeader('math.h'):
         Exit(1)

      if not conf.CheckLibWithHeader("SDL", "SDL/SDL.h", "C"):
         Exit(1)

      if not conf.CheckLibWithHeader("SDL_image", "SDL/SDL_image.h", "C"):
           Exit(1)

      if not conf.CheckCHeader('xmms/plugin.h'):
         Exit(1)

      if not conf.CheckCHeader('xmms/util.h'):
         Exit(1)

      env = conf.Finish()


      # src/config.h contains compile time specific definitions
      conf_file = open(conf_header, 'w', 1)
      conf_file.write('#define VERSION ' + str(env['VERSION']) + '\n')
      conf_file.write('#define CVERSION "' + str(env['VERSION']) + '"\n')
      conf_file.write('#define SUBDIR "' + sub_dir_name + '"\n')
      conf_file.write('#define LIBDIR "' + inst_dir + '"\n')
      conf_file.close()


   # endif
   # This part must be processed even when we want cleaning


   # We need a shared library for xmms to use
   print("")

   xmmss_lib = env.SharedLibrary(libname, [build_dir + 'xmmss.c'])
   print("Shared library to be built: " + str(xmmss_lib[0]))


   # Finaly we want to install the new plugin
   if 'install' in COMMAND_LINE_TARGETS:
      print("Installation directory: " + inst_dir)

      doc_files = glob.glob('doc/*')
      img_files = glob.glob('img/*')

      if not os.access(inst_dir1, os.F_OK):
         os.mkdir(inst_dir1)

      env.Install(inst_dir, [xmmss_lib])
      env.Install(inst_dir1, [doc_files, img_files])

      env.Alias('install', inst_dir)


   # Or uninstall, who knows?
   if 'uninstall' in COMMAND_LINE_TARGETS:
      env.Alias('uninstall', inst_dir1)
      print("Uninstalling the Plugin")

      if inst_dir1 == "/":
         print("Can't uninstall since your installation dir is the root directory!")
         print("This could easily erase all your files!")
         Exit(1)

      for root, dirs, files in os.walk(inst_dir1, topdown=False):
         for name in files:
            os.remove(os.path.join(root, name))
         for name in dirs:
            os.rmdir(os.path.join(root, name))

      os.rmdir(inst_dir1)

      lib_file = str(xmmss_lib[0])
      lib_file = lib_file.replace(build_dir, '')
      lib_file = os.path.join(inst_dir, lib_file)
      os.remove(lib_file)


   print("")
   #endif
