from parallels.common.utils import plesk_utils
from parallels.target_panel_plesk.import_api.import_api_base import \
		PleskBaseImportAPI
from parallels.common.import_api.utils import plesk_windows_change_sysuser_login, plesk_windows_get_dedicated_app_pool_user

class PleskWindowsImportAPI(PleskBaseImportAPI):
	def change_sysuser_login(self, subscription_name, sysuser_login):
		with self.conn.main_node_runner() as runner:
			plesk_windows_change_sysuser_login(runner, subscription_name, sysuser_login)

	def repair_webspace_security(self, domain_name):
		with self.conn.main_node_runner() as main_node_runner:
			product_root_dir = plesk_utils.get_windows_plesk_dir(main_node_runner)
			for _ in xrange(2):
				# Call repair webspace security twice, because there are issues
				# when restoring permissions on subdomains when migrating from
				# Plesk 8. If you call the utility once, it could set invalid
				# permissions, which causes some subdomains to response with
				# 500 status code.
				main_node_runner.run(
					ur'%s\bin\repair' % product_root_dir, 
					[
						'--repair-webspace-security', 
						'-webspace-name', domain_name
					]
				)

	def update_webspace_subdomains_security_metadata_location(self, domain_name):
		with self.conn.main_node_runner() as main_node_runner:
			product_root_dir = plesk_utils.get_windows_plesk_dir(main_node_runner)
			main_node_runner.run(ur'%s\bin\repair' % product_root_dir, ['--update-webspace-subdomains-security-metadata-location', '-webspace-name', domain_name])

	def get_dedicated_app_pool_user(self, subscription_name):
		with self.conn.main_node_runner() as runner:
			return plesk_windows_get_dedicated_app_pool_user(runner, subscription_name)

	def refresh_node_components(self, node):
		with node.runner() as runner:
			plesk_root = plesk_utils.get_windows_plesk_dir(runner)
			runner.sh(ur'"%s\admin\bin\defpackagemng" --get --force' % plesk_root)

