#!/usr/bin/python

#
# Development Order #5:
#
# This is the meat and bones of the tool, where the actual desired
# commands or operation will be run. The results are then recorded
# and added to the 'results' JSON data, which will then be sent
# back to the test. Both system and api are able to be used here.
#

import os
import sys
import time
import json
import datetime
import subprocess

import pscheduler

# from stdin
input = pscheduler.json_load(exit_on_error=True)
log = pscheduler.Log(prefix='ftp', quiet=True)

# Take input from test spec
try:
    dest = input['test']['spec']['dest']

    source = input['test']['spec']['source']
    
    # The directory to put the new copy of file (optional)
    dest_path = input['test']['spec']['dest-path']

    # Delete transfered file after transfer if cleanup == True
    cleanup = input['test']['spec']['cleanup']

except KeyError as e:
    print(e);	pscheduler.fail('Missing data in input')


timeout_iso = input['test']['spec'].get('timeout', 'PT10S')

timeout = pscheduler.timedelta_as_seconds( \
               pscheduler.iso8601_as_timedelta(timeout_iso))

start_time = datetime.datetime.now()
succeeded = False
error = ''
diags = ''

STDERR = ""

# Run the actual task here:
if True:
  # Execute curl command
  argv = ['curl',
          '-o',   # Flag to output file
          dest,   # Download location
	  source] # Source URL
  

  status, stdout, stderr = pscheduler.run_program(argv, timeout=timeout)

  lines = stderr.split('\r')
  parsed = [stat for stat in lines[-1].split(' ') if stat != '']
  
  STDERR = parsed

  if status:
    succeeded = False
    error = "Error running program:\n%s"% stderr.strip('\n')

    # Determine how much (if any) of the file was transferred
    if os.path.isfile(dest):
      bytes_sent = os.stat(dest).st_size

      # Convert bytes to human readable format 
      # TODO: The pscheduler module has functions for doing this.
      scalar = ['B', 'KB', 'MB', 'GB', 'TB']
      while bytes_sent > 1024 and len(scalar) > 1:
        bytes_sent /= 1024; scalar = scalar[1:]

      # Put this into diags
      #error += '\n\nBytes Transfered: %s %s'% (int(bytes_sent), scalar[0])
      #error += '\n\nActual Timeout: %s seconds' % timeout
      
      # Getting source filesize
      #argv = ['curl', '-s', source, '| wc -c']
      #outs = pscheduler.run_program(argv, timeout=timeout)
      #error += '\n\n' + str(outs)

  else:
    succeeded = True
    diags = stdout

    if cleanup is True:
      if os.path.isfile(dest): os.remove(dest)

end_time = datetime.datetime.now()

# Organize results into json data
final_results = {
    'succeeded': succeeded,
    'error': error,
    'diags': diags }

results = {'schema': 1, 
	   'succeeded': succeeded}

results['time'] = pscheduler.timedelta_as_iso8601( end_time - start_time)

'''# Logging
with open('/tmp/run.log', 'wb') as f:
  f.write('LOGGING ftp/run')
  f.write(str(STDERR))
'''

#%#%#%#%#%#
#STDERR[6] is Average Download Speed

results['throughput'] = STDERR[-1].split('\n')[0]

#%#%#%#%#%#

results['bytes-sent'] = STDERR[1]

final_results['result'] = results
pscheduler.succeed_json(final_results)



#?
