#!/usr/bin/env python

import os
import subprocess
import sys
import socket
import logging
import logging.handlers

from distutils import spawn 
from packaging.version import Version, LegacyVersion

log = logging.getLogger('daacpull')
log.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address='/dev/log')
formatter = logging.Formatter('%(module)s.%(funcName)s: %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)

def execute_shell(args, shell=False, cwd=None):
    """Execute the given command in the shell."""
    proc = subprocess.Popen(args,
                            shell=shell,
                            cwd=cwd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            universal_newlines=True)
    output, errors = proc.communicate()

    log.error(errors)

    return output

try:

   #Get the puppet location
   p_location = spawn.find_executable("puppet")
   g_location = spawn.find_executable("git")

   # Check if file exists and version number of puppet
   if os.path.exists(p_location):
      p_version = subprocess.check_output([p_location, "-V"], shell=False).rstrip('\n')
   else:
      sys.exit("Puppet is not installed")

   # Define the where to daacpull
   if Version(p_version) < Version('4'):
           repo_path = '/etc/puppet'
   elif Version(p_version) > Version('4'):
           repo_path = '/etc/puppetlabs/code'
   else:   
           sys.exit("This script is not compatible")

   # Define the Branch to follow
   p_branch = socket.getfqdn().split('.')[0].split('-')[-1]

   if p_branch != 'dev':
           p_branch = 'master'

   # Working on Git Repository.
   log.info(execute_shell(args=[g_location, "stash"], cwd=repo_path))
   log.info(execute_shell(args=[g_location, "submodule", "foreach", "git", "reset", "--hard"], cwd=repo_path))
   log.info(execute_shell(args=[g_location, "submodule", "sync"], cwd=repo_path))
   log.info(execute_shell(args=[g_location, "pull", "origin", p_branch], cwd=repo_path))
   log.info(execute_shell(args=[g_location, "submodule", "update", "--init"], cwd=repo_path))

except Exception as e:
    log.exception('An Error Occured:')
