from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from xvfbwrapper import Xvfb

import os
import Queue
import time
import subprocess
import sys

def umc_logon(username, pw):
	with Xvfb():
		options = webdriver.ChromeOptions()
		options.add_argument('--no-sandbox')
		try:
			driver = webdriver.Chrome(chrome_options=options)
			driver.get('https://10.200.7.160/univention/portal/')
			WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="umcLoginButton_label"]'))).click()
			WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="umcLoginUsername"]'))).send_keys(username)
			WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="umcLoginPassword"]'))).send_keys(pw)
			elem = driver.find_elements_by_id('umcLoginSubmit')[0]
			elem.click()
			time.sleep(3)
			WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="umcLoginButton_label"]'))).click()
		finally:
			print('UMC Logon with {} done'.format(username))
			driver.quit()

subprocess.check_call(['service', 'univention-management-console-server', 'restart'])
time.sleep(2)
for i in range(0, 4):
	umc_logon('fb12', 'univention')
time.sleep(60)
subprocess.check_call(['service', 'slapd', 'restart'])
umc_logon('fb12', 'univention')
umc_pid = subprocess.check_output(['pidof', '-x', 'univention-management-console-server']).strip()
umc_lsof = subprocess.check_output(['lsof', '-p', umc_pid])
close_wait = 0
for line in umc_lsof.split('\n'):
	if 'CLOSE_WAIT' in line:
		close_wait += 1
if close_wait > 0:
	print('found {} close wait'.format(close_wait))
	sys.exit(1)
