#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 2010-2011 Nico Schottelius (nico-cdist at schottelius.org)
#
# This file is part of cdist.
#
# cdist 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.
#
# cdist 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 cdist. If not, see <http://www.gnu.org/licenses/>.
#
#

import argparse
import datetime
import logging
import multiprocessing
import os
import subprocess
import shutil
import stat
import sys
import tempfile

BANNER = """
             ..          .       .x+=:.        s
           dF           @88>    z`    ^%      :8
          '88bu.        %8P        .   <k    .88
      .   '*88888bu      .       .@8Ned8"   :888ooo
 .udR88N    ^"*8888N   .@88u   .@^%8888"  -*8888888
<888'888k  beWE "888L ''888E` x88:  `)8b.   8888
9888 'Y"   888E  888E   888E  8888N=*8888   8888
9888       888E  888E   888E   %8"    R88   8888
9888       888E  888F   888E    @8Wou 9%   .8888Lu=
?8888u../ .888N..888    888&  .888888P`    ^%888*
 "8888P'   `"888*""     R888" `   ^"F        'Y"
   "P'        ""         ""
"""

# Given paths from installation
REMOTE_BASE_DIR            = "/var/lib/cdist"
REMOTE_CONF_DIR            = os.path.join(REMOTE_BASE_DIR, "conf")
REMOTE_OBJECT_DIR          = os.path.join(REMOTE_BASE_DIR, "object")
REMOTE_TYPE_DIR            = os.path.join(REMOTE_CONF_DIR, "type")
REMOTE_GLOBAL_EXPLORER_DIR = os.path.join(REMOTE_CONF_DIR, "explorer")

CODE_HEADER                = "#!/bin/sh -e\n"
DOT_CDIST                  = ".cdist"
VERSION                    = "2.0.0"

logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
log = logging.getLogger()


class TypeEmulator:
   def __init__(self, name):
      self.name = name
      self.type = os.path.basename(name)


   def type_emulator(self):
      type = basename(sys.argv[0])

      type_is_singleton(type)

      # Check object id

      # Prevent double slash if id begins with /

      # Record parameter: opt_file="${opt#--}"
      # [ $# -ge 1 ] || __cdist_usage "Missing value for $opt"
      # echo "${value}" > "${__cdist_parameter_dir}/${opt_file}"

      # Record requirements
      # echo $requirement >> "$(__cdist_object_require "$__cdist_object_self")"

      # Ensure required parameters are given
      # Ensure that only optional or required parameters are given
      # [ "$is_valid" ] || __cdist_usage "Unknown parameter $parameter"

      # Merge object (creating twice with the same parameter + requirements == allowed)

      # diff -ru "${__cdist_new_object_dir}/${__cdist_name_parameter}
      # # Add "I was here message"
      # _cdist_object_source_add "${__cdist_object_dir}"

class Cdist:
   """Cdist main class to hold arbitrary data"""

   def __init__(self, target_host, 
               initial_manifest=False, remote_user="root",
               home=None, debug=False):
      self.target_host = target_host
      self.remote_prefix = ["ssh", "root@" + self.target_host]

      # Setup directory paths
      self.temp_dir = tempfile.mkdtemp()

      self.debug = debug
      
      if home:
         self.base_dir = home
      else:
         self.base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))

      self.conf_dir              = os.path.join(self.base_dir, "conf")
      self.cache_base_dir        = os.path.join(self.base_dir, "cache")
      self.cache_dir             = os.path.join(self.cache_base_dir, self.target_host)
      self.global_explorer_dir   = os.path.join(self.conf_dir, "explorer")
      self.lib_dir               = os.path.join(self.base_dir, "lib")
      self.manifest_dir          = os.path.join(self.conf_dir, "manifest")
      self.type_base_dir         = os.path.join(self.conf_dir, "type")

      self.out_dir = os.path.join(self.temp_dir, "out")
      os.mkdir(self.out_dir)

      self.global_explorer_out_dir = os.path.join(self.out_dir, "explorer")
      os.mkdir(self.global_explorer_out_dir)

      self.object_base_dir = os.path.join(self.out_dir, "object")

      # Setup binary directory + contents
      self.bin_dir = os.path.join(self.out_dir, "bin")
      os.mkdir(self.bin_dir)
      self.link_type_to_emulator()

      # List of type explorers transferred
      self.type_explorers_transferred = {}

      # objects
      self.objects_prepared = []

      self.remote_user = remote_user

      # Mostly static, but can be overwritten on user demand
      if initial_manifest:
         self.initial_manifest = initial_manifest
      else:
         self.initial_manifest = os.path.join(self.manifest_dir, "init")

   def cleanup(self):
      # Do not use in __del__:
      # http://docs.python.org/reference/datamodel.html#customization
      # "other globals referenced by the __del__() method may already have been deleted 
      # or in the process of being torn down (e.g. the import machinery shutting down)"
      #
      log.debug("Saving" + self.temp_dir + "to " + self.cache_dir)
      # Remove previous cache
      if os.path.exists(self.cache_dir):
         shutil.rmtree(self.cache_dir)
      shutil.move(self.temp_dir, self.cache_dir)

   def exit_error(self, *args):
      log.error(*args)
      sys.exit(1)

   def remote_mkdir(self, directory):
      """Create directory on remote side"""
      self.run_or_fail(["mkdir", "-p", directory], remote=True)

   def remote_cat(filename):
      """Use cat on the remote side for output"""
      self.run_or_fail(["cat", filename], remote=True)

   def shell_run_or_debug_fail(self, script, *args, **kargs):
      # Manually execute /bin/sh, because sh -e does what we want
      # and sh -c -e does not exit if /bin/false called
      args[0][:0] = [ "/bin/sh", "-e" ]

      remote = False
      if "remote" in kargs:
         if kargs["remote"]:
            args[0][:0] = self.remote_prefix
            remote = true

         del kargs["remote"]

      log.debug("Shell exec cmd: %s", args)
      log.debug("Shell exec env: %s", kargs['env'])
      try:
         subprocess.check_call(*args, **kargs)
      except subprocess.CalledProcessError:
         log.error("Code that raised the error:\n")
         if remote:
            remote_cat(script)
         else:
            script_fd = open(script)
            print(script_fd.read())
            script_fd.close()

         self.exit_error("Command failed (shell): " + " ".join(*args))

   def run_or_fail(self, *args, **kargs):
      if "remote" in kargs:
         if kargs["remote"]:
            args[0][:0] = self.remote_prefix

         del kargs["remote"]

      log.debug("Exec: " + " ".join(*args))
      try:
         subprocess.check_call(*args, **kargs)
      except subprocess.CalledProcessError:
         self.exit_error("Command failed: " + " ".join(*args))

   def remove_remote_dir(self, destination):
      self.run_or_fail(["rm", "-rf",  destination], remote=True)

   def transfer_dir(self, source, destination):
      """Transfer directory and previously delete the remote destination"""
      self.remove_remote_dir(destination)
      self.run_or_fail(["scp", "-qr", source, 
                        self.remote_user + "@" + 
                        self.target_host + ":" + 
                        destination])

   def transfer_file(self, source, destination):
      """Transfer file"""
      self.run_or_fail(["scp", "-q", source, 
                        self.remote_user + "@" +
                        self.target_host + ":" +
                        destination])

   def global_explorer_output_path(self, explorer):
      """Returns path of the output for a global explorer"""
      return os.path.join(self.global_explorer_out_dir, explorer)

   def type_explorer_output_dir(self, cdist_object):
      """Returns and creates dir of the output for a type explorer"""
      dir = os.path.join(self.object_dir(cdist_object), "explorer")
      if not os.path.isdir(dir):
         os.mkdir(dir)

      return dir

   def remote_global_explorer_path(self, explorer):
      """Returns path to the remote explorer"""
      return os.path.join(REMOTE_GLOBAL_EXPLORER_DIR, explorer)

   def list_global_explorers(self):
      """Return list of available explorers"""
      return os.listdir(self.global_explorer_dir)

   def list_type_explorers(self, type):
      """Return list of available explorers for a specific type"""
      dir = self.type_explorer_dir(type)
      if os.path.isdir(dir):
         list = os.listdir(dir)
      else:
         list = []

      log.debug("Explorers for %s in %s: %s", type, dir, list)

      return list

   def list_types(self):
      return os.listdir(self.type_base_dir)

   def list_object_paths(self, starting_point):
      """Return list of paths of existing objects"""
      object_paths = []

      for content in os.listdir(starting_point):
         full_path = os.path.join(starting_point, content)
         if os.path.isdir(full_path):
            object_paths.extend(self.list_object_paths(starting_point = full_path))

         # Directory contains .cdist -> is an object
         if content == DOT_CDIST:
            object_paths.append(starting_point)

      return object_paths

   def get_type_from_object(self, cdist_object):
      """Returns the first part (i.e. type) of an object"""
      return cdist_object.split(os.sep)[0]

   def get_object_id_from_object(self, cdist_object):
      """Returns everything but the first part (i.e. object_id) of an object"""
      return os.sep.join(cdist_object.split(os.sep)[1:])

   def object_dir(self, cdist_object):
      """Returns the full path to the object (including .cdist)"""
      return os.path.join(self.object_base_dir, cdist_object, DOT_CDIST)

   def remote_object_dir(self, cdist_object):
      """Returns the remote full path to the object (including .cdist)"""
      return os.path.join(REMOTE_OBJECT_DIR, cdist_object, DOT_CDIST)

   def object_parameter_dir(self, cdist_object):
      """Returns the dir to the object parameter"""
      return os.path.join(self.object_dir(cdist_object), "parameter")

   def remote_object_parameter_dir(self, cdist_object):
      """Returns the remote dir to the object parameter"""
      return os.path.join(self.remote_object_dir(cdist_object), "parameter")

   def object_code_paths(self, cdist_object):
      """Return paths to code scripts of object"""
      return [os.path.join(self.object_dir(cdist_object), "code-local"),
              os.path.join(self.object_dir(cdist_object), "code-remote")]

   def list_objects(self):
      """Return list of existing objects"""

      objects = []
      if os.path.isdir(self.object_base_dir):
         object_paths = self.list_object_paths(self.object_base_dir)

         for path in object_paths:
            objects.append(os.path.relpath(path, self.object_base_dir))

      return objects

   def type_dir(self, type):
      """Return directory the type"""
      return os.path.join(self.type_base_dir, type)

   def type_explorer_dir(self, type):
      """Return directory that holds the explorers of a type"""
      return os.path.join(self.type_dir(type), "explorer")

   def type_gencode_paths(self, type):
      """Return paths to gencode scripts of type"""
      return [os.path.join(self.type_base_dir, type, "gencode-local"),
              os.path.join(self.type_base_dir, type, "gencode-remote")]

   def type_manifest_path(self, type):
      """Return path to manifest of type"""
      return os.path.join(self.type_base_dir, type, "manifest")

   def remote_type_explorer_dir(self, type):
      """Return remote directory that holds the explorers of a type"""
      return os.path.join(REMOTE_TYPE_DIR, type, "explorer")

   def transfer_object_parameter(self, cdist_object):
      """Transfer the object parameter to the remote destination"""
      # Create base path before using mkdir -p
      self.remote_mkdir(self.remote_object_parameter_dir(cdist_object))

      # Synchronise parameter dir afterwards
      self.transfer_dir(self.object_parameter_dir(cdist_object), 
                        self.remote_object_parameter_dir(cdist_object))

   def transfer_global_explorers(self):
      """Transfer the global explorers"""
      self.remote_mkdir(REMOTE_GLOBAL_EXPLORER_DIR)
      self.transfer_dir(self.global_explorer_dir, REMOTE_GLOBAL_EXPLORER_DIR)

   def transfer_type_explorers(self, type):
      """Transfer explorers of a type, but only once"""
      if type in self.type_explorers_transferred:
         log.debug("Skipping retransfer for explorers of %s", type)
         return
      else:
         # Do not retransfer
         self.type_explorers_transferred[type] = 1

      src = self.type_explorer_dir(type)
      remote_base = os.path.join(REMOTE_TYPE_DIR, type)
      dst = self.remote_type_explorer_dir(type)

      # Only continue, if there is at least the directory
      if os.path.isdir(src):
         # Ensure that the path exists
         self.remote_mkdir(remote_base)
         self.transfer_dir(src, dst)


   def link_type_to_emulator(self):
      """Link type names to cdist-type-emulator"""
      for type in self.list_types():
         source = os.path.join(self.lib_dir, "cdist-type-emulator")
         destination = os.path.join(self.bin_dir, type)
         log.debug("Linking %s to %s", source, destination)
         os.symlink(source, destination)

   def run_global_explores(self):
      """Run global explorers"""
      explorers = self.list_global_explorers()
      if(len(explorers) == 0):
         self.exit_error("No explorers found in", self.global_explorer_dir)

      self.transfer_global_explorers()
      for explorer in explorers:
         output = self.global_explorer_output_path(explorer)
         output_fd = open(output, mode='w')
         cmd = []
         cmd.append("__explorer=" + REMOTE_GLOBAL_EXPLORER_DIR)
         cmd.append(self.remote_global_explorer_path(explorer))

         self.run_or_fail(cmd, stdout=output_fd, remote=True)
         output_fd.close()

   def run_type_explorer(self, cdist_object):
      """Run type specific explorers for objects"""
      # Based on bin/cdist-object-explorer-run

      # Transfering explorers for this type
      type = self.get_type_from_object(cdist_object)
      self.transfer_type_explorers(type)

      cmd = []
      cmd.append("__explorer="      + REMOTE_GLOBAL_EXPLORER_DIR)
      cmd.append("__type_explorer=" + self.remote_type_explorer_dir(type))
      cmd.append("__object="        + self.remote_object_dir(cdist_object))
      cmd.append("__object_id="     + self.get_object_id_from_object(cdist_object))
      cmd.append("__object_fq="     + cdist_object)

      # Need to transfer at least the parameters for objects to be useful
      self.transfer_object_parameter(cdist_object)

      explorers = self.list_type_explorers(type)
      for explorer in explorers:
         remote_cmd = cmd + [os.path.join(self.remote_type_explorer_dir(type), explorer)]
         output = os.path.join(self.type_explorer_output_dir(cdist_object), explorer)
         output_fd = open(output, mode='w')
         log.debug("%s exploring %s using %s storing to %s", 
                  cdist_object, explorer, remote_cmd, output)
                  
         self.run_or_fail(remote_cmd, stdout=output_fd, remote=True)
         output_fd.close()

   def init_deploy(self):
      """Ensure the base directories are cleaned up"""
      log.debug("Creating clean directory structure")

      self.remove_remote_dir(REMOTE_BASE_DIR)
      self.remote_mkdir(REMOTE_BASE_DIR)

   def run_initial_manifest(self):
      """Run the initial manifest"""
      env = {  "__manifest" : self.manifest_dir }
      self.run_manifest(self.initial_manifest, extra_env=env)

   def run_type_manifest(self, cdist_object):
      """Run manifest for a specific object"""
      type = self.get_type_from_object(cdist_object)
      manifest = self.type_manifest_path(type)
      
      log.debug("%s: Running %s", cdist_object, manifest)
      if os.path.exists(manifest):
         env = {  "__object" :   self.object_dir(cdist_object), 
                  "__object_id": self.get_object_id_from_object(cdist_object),
                  "__object_fq": cdist_object,
                  "__type":      self.type_dir(type)
               }
         self.run_manifest(manifest, extra_env=env)

   def run_manifest(self, manifest, extra_env=None):
      """Run a manifest"""
      log.debug("Running manifest %s, env=%s", manifest, extra_env)
      env = os.environ.copy()
      env['PATH'] = self.bin_dir + ":" + env['PATH']

      env['__target_host']    = self.target_host
      env['__global']         = self.out_dir
      
      # Legacy stuff to make cdist-type-emulator work
      env['__cdist_conf_dir']       = self.conf_dir
      env['__cdist_core_dir']       = os.path.join(self.base_dir, "core")
      env['__cdist_local_base_dir'] = self.temp_dir
      env['__cdist_manifest']       = self.initial_manifest

      # Other environment stuff
      if extra_env:
         env.update(extra_env)

      self.shell_run_or_debug_fail(manifest, [manifest], env=env)

   def list_object_requirements(self, cdist_object):
      """Return list of requirements for specific object"""
      file=os.path.join(self.object_dir(cdist_object), "require")

      if os.path.isfile(file):
         file_fd = open(file, "r")
         requirements = file_fd.readlines()
         file_fd.close()

         # Remove \n from all lines
         requirements = map(lambda s: s.strip(), requirements)

         log.debug("Requirements for %s: %s", cdist_object, requirements)
      else:
         requirements = []

      return requirements

   def object_run(self, cdist_object, mode):
      """Run gencode or code for an object"""
      log.debug("Running %s from %s", mode, cdist_object)
      requirements = self.list_object_requirements(cdist_object)
         
      for requirement in requirements:
         log.debug("Object %s requires %s", cdist_object, requirement)
         self.object_run(requirement, mode=mode)

      #
      # Setup env Variable:
      # 
      env = os.environ.copy()
      env['__target_host'] = self.target_host
      env['__global']      = self.out_dir
      env["__object"]      = self.object_dir(cdist_object)
      env["__object_id"]   = self.get_object_id_from_object(cdist_object)
      env["__object_fq"]   = cdist_object

      if mode == "gencode":
         paths = self.type_gencode_paths(self.get_type_from_object(cdist_object))
         for bin in paths:
            if os.path.isfile(bin):
               # omit "gen" from gencode and 
               outfile=os.path.join(self.object_dir(cdist_object), 
                  os.path.basename(bin)[3:])

               outfile_fd = open(outfile, "w")

               # Need to flush to ensure our write is done before stdout write
               outfile_fd.write(CODE_HEADER)
               outfile_fd.flush()

               self.shell_run_or_debug_fail(bin, [bin], env=env, stdout=outfile_fd)
               outfile_fd.close()

               status = os.stat(outfile)

               # Remove output if empty, else make it executable
               if status.st_size == len(CODE_HEADER):
                  os.unlink(outfile)
               else:
                  # Add header and make executable - identically to 0o700
                  os.chmod(outfile, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR)

      if mode == "code":
         local_dir   = self.object_dir(cdist_object)
         remote_dir  = self.remote_object_dir(cdist_object)

         bin = os.path.join(local_dir, "code-local")
         if os.path.isfile(bin):
            self.run_or_fail([bin], remote=False)
            

         local_remote_code = os.path.join(local_dir, "code-remote")
         remote_remote_code = os.path.join(remote_dir, "code-remote")
         if os.path.isfile(local_remote_code):
            self.transfer_file(local_remote_code, remote_remote_code)
            self.run_or_fail([remote_remote_code], remote=True)
            
   def deploy_to(self):
      """Mimic the old deploy to: Deploy to one host"""
      log.info("Deploying to " + self.target_host)
      time_start = datetime.datetime.now()
      self.init_deploy()
      self.run_global_explores()
      self.run_initial_manifest()
      
      old_objects = []
      objects = self.list_objects()

      # Continue process until no new objects are created anymore
      while old_objects != objects:
         log.debug("Prepare stage")
         old_objects = list(objects)
         for cdist_object in objects:
            if cdist_object in self.objects_prepared:
               log.debug("Skipping rerun of object %s", cdist_object)
               continue
            else:
               self.run_type_explorer(cdist_object)
               self.run_type_manifest(cdist_object)
               self.objects_prepared.append(cdist_object)

         objects = self.list_objects()
      
      log.debug("Actual run objects")
      # Now do the final steps over the existing objects
      for cdist_object in objects:
         log.debug("Run object: %s", cdist_object)
         self.object_run(cdist_object, mode="gencode")
         self.object_run(cdist_object, mode="code")

      time_end = datetime.datetime.now()
      duration = time_end - time_start
      log.info("Finished run of %s in %s seconds", 
         self.target_host,
         duration.total_seconds())

   def deploy_and_cleanup(self):
      """Do what is most often done: deploy & cleanup"""
      self.deploy_to()
      self.cleanup()

def banner(args):
   """Guess what :-)"""
   print(BANNER)
   sys.exit(0)

def config(args):
   """Configure remote system"""
   process = {}

   time_start = datetime.datetime.now()

   for host in args.host:
      c = Cdist(host, initial_manifest=args.manifest, home=args.cdist_home, debug=args.debug)
      if args.parallel:
         log.debug("Creating child process for %s", host)
         process[host] = multiprocessing.Process(target=c.deploy_and_cleanup)
         process[host].start()
      else:
         c.deploy_and_cleanup()

   if args.parallel:
      for p in process.keys():
         log.debug("Joining %s", p)
         process[p].join()

   time_end = datetime.datetime.now()
   log.info("Total processing time for %s host(s): %s", len(args.host),
            (time_end - time_start).total_seconds())

if __name__ == "__main__":
   # Construct parser others can reuse
   parser = {}
   # Options _all_ parsers have in common
   parser['most'] = argparse.ArgumentParser(add_help=False)
   parser['most'].add_argument('-d', '--debug',
      help='Set log level to debug', action='store_true')

   # Main subcommand parser
   parser['main'] = argparse.ArgumentParser(description='cdist ' + VERSION)
   parser['main'].add_argument('-V', '--version',
      help='Show version', action='version',
      version='%(prog)s ' + VERSION)
   parser['sub'] = parser['main'].add_subparsers(title="Commands")

   # Banner
   parser['banner'] = parser['sub'].add_parser('banner', 
      add_help=False)
   parser['banner'].set_defaults(func=banner)

   # Config
   parser['config'] = parser['sub'].add_parser('config',
      parents=[parser['most']])
   parser['config'].add_argument('host', nargs='+',
      help='one or more hosts to operate on')
   parser['config'].add_argument('-c', '--cdist-home',
       help='Change cdist home (default: .. from bin directory)',
       action='store')
   parser['config'].add_argument('-i', '--initial-manifest', 
       help='Path to a cdist manifest',
       dest='manifest', required=False)
   parser['config'].add_argument('-p', '--parallel',
       help='Operate on multiple hosts in parallel',
       action='store_true', dest='parallel')
   parser['config'].add_argument('-s', '--sequential',
       help='Operate on multiple hosts sequentially (default)',
       action='store_false', dest='parallel')
   parser['config'].set_defaults(func=config)

   for p in parser:
      parser[p].epilog = "Get cdist at http://www.nico.schottelius.org/software/cdist/"

   args = parser['main'].parse_args(sys.argv[1:])

   # Most subcommands have --debug, so handle it here
   if 'debug' in args:
      if args.debug:
         logging.root.setLevel(logging.DEBUG)
   log.debug(args)

   try:
      args.func(args)
   except KeyboardInterrupt:
       sys.exit(0)
