#!{{ python_executable }}

SMARCTBIN={{ smartctl_binary }}
LOGFOLDER={{ monitor_log_directory }}

import subprocess
import logging
import os

logger = logging.getLogger("SMARTMON")
logger.setLevel(logging.DEBUG)

ch = logging.FileHandler(os.path.join(LOGFOLDER, "smartmontools.log"))
ch.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

ch.setFormatter(formatter)
logger.addHandler(ch)

def _call(cmd):
  p = subprocess.Popen(
     cmd,
     stdout=subprocess.PIPE,
     stdin=subprocess.PIPE,
     shell=True)

  return p.communicate()

def get_disk_list():
  output, err = _call("%s --scan" % SMARCTBIN)
  disk_list = []
  for line in output.split("\n"):
    if line != '':
      disk_path = line.split(" ")[0]
      if disk_path.startswith("/dev/"):
        disk_list.append(disk_path)

  return disk_list

logger.debug("Starting new Data collection.")

disk_list = get_disk_list()

logger.debug("Identified disks: %s" % disk_list)

for disk in disk_list:
  logger.info("Starting test for %s" % disk)
  output, err = _call("%s --all %s" % (SMARCTBIN, disk))
  for l in output.split("\n"):
    logger.info("%s - %s" % (disk, l))
  if err is not None:
    logger.warning(err)

logger.debug("Stopped to Collect Data.")
