#!/usr/bin/python3

import pytest
import subprocess

def test_write_telegraf_conf():

  # test telegraf monitoring configuration
  TELEGRAF_CONF_DIR="/etc/telegraf"
  LOCATION="DC1"
  SFC_ID="media_service_A"
  SFC_ID_INSTANCE="media_service_A_instance"
  SF_ID="streaming_service"
  SF_ID_INSTANCE="streaming_service_instance"
  IP_ENDPOINT_ID="endpoint"
  INFLUXDB_URL="http://172.29.236.10"
  DATABASE_NAME="experimentation_database"  

  try:
    # run write config template script with no telegraf conf directory
    cmd = 'sudo /vagrant/scripts/clmc-agent/configure_template.sh'
    (out, err, code) = run_command(cmd)
    assert code == 1, "Failed to catch error of no telegraf configuration directory : " + str(code) + ", cmd=" + cmd

    # mk telegraf conf directory
    run_command("sudo mkdir -p /etc/telegraf")

    # run write config template  script with no telegraf.d directory
    (out, err, code) = run_command(cmd)
    assert code == 1, "Failed to catch error of no telegraf include directory : " + str(code) + ", cmd=" + cmd

    # mk telegraf.d directory
    run_command("sudo mkdir -p /etc/telegraf/telegraf.d")    

    # run write config template script and check that the script has exited correctly
    (out, err, code) = run_command(cmd)
    assert code == 0, "Failed to write configuration files : " + str(code) + ", cmd=" + cmd

    # run template relacement script with incorrect arguments
    cmd = 'sudo /vagrant/scripts/clmc-agent/configure.sh' 
    (out, err, code) = run_command(cmd)
    assert code == 1, "Failed to return error on incorrect arguments : " + str(code) + ", cmd=" + cmd  

    # run template relacement script with all arguments
    cmd = 'sudo /vagrant/scripts/clmc-agent/configure.sh ' + LOCATION + ' ' + SFC_ID + ' ' + SFC_ID_INSTANCE + ' ' + SF_ID + ' ' + SF_ID_INSTANCE + ' ' + IP_ENDPOINT_ID + ' ' + INFLUXDB_URL + ' ' + DATABASE_NAME
    (out, err, code) = run_command(cmd)
    assert code == 0, "Configure command returned error, output=" + str(out) + ", cmd=" + cmd

    # check that replacement was correct in telegraf.conf
    try:        
        TELEGRAF_GENERAL_CONF_FILE = TELEGRAF_CONF_DIR + "/telegraf.conf"
        with open(TELEGRAF_GENERAL_CONF_FILE) as general_conf:
          lines = general_conf.read()          
          assert lines.find(LOCATION), "Cannot find location" 
          assert lines.find(SFC_ID), "Cannot find sfc_id"
          assert lines.find(SFC_ID_INSTANCE), "Cannot find sfc_id_instance"  
          assert lines.find(SF_ID), "Cannot find sfc_id"            
          assert lines.find(SF_ID_INSTANCE), "Cannot find sf_id_instance"
          assert lines.find(IP_ENDPOINT_ID), "Cannot find location"                      
    except FileNotFoundError:
        assert False, "Telegraf general conf file not found, " + TELEGRAF_GENERAL_CONF_FILE

    # check that replacement was correct in telegraf_output.conf
    try:
        TELEGRAF_OUTPUT_CONF_FILE = TELEGRAF_CONF_DIR + "/telegraf.d/telegraf_output.conf"
        with open(TELEGRAF_OUTPUT_CONF_FILE) as output_conf:
          lines = output_conf.read()
          assert lines.find(INFLUXDB_URL), "Cannot find influx_db" 
          assert lines.find(DATABASE_NAME), "Cannot find database"                    
    except FileNotFoundError:
        assert False, "Telegraf output conf file not found, " + TELEGRAF_OUTPUT_CONF_FILE

  finally:
      # clean up telegraf after test
      run_command("sudo rm -rf /etc/telegraf")
      print ("finally")

# wrapper for executing commands on the cli, returning (std_out, std_error, process_return_code)
def run_command(cmd):
    """Run a shell command.

    Arguments:
        cmd {string} -- command to run in the shell

    Returns:
        stdout, stderr, exit code -- tuple of the process's stdout, stderr and exit code (0 on success)
    """
    proc = subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True)
    out, err = proc.communicate()
    return_code = proc.returncode
    return out, err, return_code