#!/usr/bin/python3

import amulet
import requests
zs_configuration = {
    'adminKeyHash': 'Z123456789012345678901234567890123456789012345678901234567890123',
    'guiPassword': 'zsGuiPass'
}
d = amulet.Deployment(series='trusty')

d.add('zend-server')
d.add('mysql')
d.expose('zend-server')
d.configure('zend-server',zs_configuration)
d.configure('mysql', {'dataset-size':'512M'})
d.relate('zend-server:database', 'mysql:db-admin')
try:
    d.setup(timeout=1100)
    d.sentry.wait()
except amulet.helpers.TimeoutError:
    amulet.raise_status(amulet.SKIP, msg="Environment wasn't stood up in time")
except:
    raise

unit = d.sentry.unit['zend-server/0']

# test we can access over http
page = requests.get('http://{}'.format(unit.info['public-address']))
page.raise_for_status()
#test Zend Server status:
command = '/usr/local/zend/bin/zendctl.sh status'
print(command)
# Run the command to get Zend Server's status.
output, code = unit.run(command)
print(output)
if code != 0 and output.find('lighttpd is running') != -1:
    message = 'Zend Server lighttpd which controls the gui is not running:\n%s' % output
    amulet.raise_status(amulet.FAIL, msg=message)
if code != 0 and output.find('zdd is running') != -1:
    message = 'Zend Server deployment daemon is not running:\n%s' % output
    amulet.raise_status(amulet.FAIL, msg=message)
if code != 0 and output.find('zsd is running') != -1:
    message = 'Zend Server daemon is not running:\n%s' % output
    amulet.raise_status(amulet.FAIL, msg=message)
command = 'service apache2 status'
print(command)
# Run the command to get Apache's status.
output, code = unit.run(command)
print(output)
if code != 0 and output.find('apache2 is running') != -1:
    message = 'Zend Server lighttpd which controls the gui is not running:\n%s' % output
    amulet.raise_status(amulet.FAIL, msg=message)

# Now you can use d.sentry.unit[UNIT] to address each of the units and perform
# more in-depth steps. There are three test statuses: amulet.PASS, amulet.FAIL,
# and amulet.SKIP - these can be triggered with amulet.raise_status(). Each
# d.sentry.unit[] has the following methods:
# - .info - An array of the information of that unit from Juju
# - .file(PATH) - Get the details of a file on that unit
# - .file_contents(PATH) - Get plain text output of PATH file from that unit
# - .directory(PATH) - Get details of directory
# - .directory_contents(PATH) - List files and folders in PATH on that unit
# - .relation(relation, service:rel) - Get relation data from return service
