import os

import parallels.core
from parallels.core.runners.base import BaseRunner
from parallels.core.runners.entities import ExecutionOptions, ControlledInterruption
from parallels.core.utils.migrator_utils import get_package_extras_file_path
from parallels.plesk.source.web.utils.copy_content.base import CopyContentBase
from parallels.plesk.source.web.utils.copy_content.ftp_migrator_utils import create_config, parse_output


class CopyContentLinuxFTP(CopyContentBase):
    def copy_folder(self, global_context, folder):
        """Run action for single migrated folder

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :type folder: parallels.plesk.source.web.migrated_folder.MigratedFolder
        :rtype: list[parallels.core.reports.model.issue.Issue] | None
        """
        source = global_context.conn.get_source()
        config_json = create_config(source, folder)

        ftp_migrator_path = get_package_extras_file_path(parallels.core, "ftp-migrator")
        ftp_migrator_executable = os.path.join(ftp_migrator_path, 'ftp-migrator')
        controlled_interruption = ControlledInterruption(stop_mark=global_context.stop_mark)

        with folder.target_server.runner() as local_runner:
            assert isinstance(local_runner, BaseRunner)
            command_results = local_runner.execute_command(
                u'su {username} --shell /bin/sh -c {command}', dict(
                    username=folder.target_sysuser_login,
                    command=u"{ftp_migrator_executable} --config-file -".format(
                        ftp_migrator_executable=ftp_migrator_executable
                    )
                ),
                ExecutionOptions(
                    stdin_content=config_json,
                    umask=0o22,
                    controlled_interruption=controlled_interruption
                )
            )

        return parse_output(command_results.stdout, command_results.stderr)
