# This file is part of Buildbot.  Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members


import os

from twisted.internet import defer
from twisted.internet import reactor

from buildbot.test.util.decorators import flaky
from buildbot.test.util.integration import RunMasterBase


# This integration test tests that the try command line works end2end
class TryClientE2E(RunMasterBase):
    timeout = 15

    @defer.inlineCallbacks
    def setup_config(self):
        c = {}
        from buildbot.config import BuilderConfig
        from buildbot.plugins import schedulers
        from buildbot.plugins import steps
        from buildbot.process.factory import BuildFactory

        c['schedulers'] = [
            schedulers.Try_Userpass(
                name="try", builderNames=["testy"], port='tcp:0', userpass=[("alice", "pw1")]
            )
        ]
        f = BuildFactory()
        f.addStep(steps.ShellCommand(command='echo hello'))
        c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)]
        yield self.setup_master(c)

    @flaky(bugNumber=7084)
    @defer.inlineCallbacks
    def test_shell(self):
        yield self.setup_config()

        def trigger_callback():
            port = self.master.pbmanager.dispatchers['tcp:0'].port.getHost().port

            def thd():
                os.system(
                    f"buildbot try --connect=pb --master=127.0.0.1:{port} -b testy "
                    "--property=foo:bar --username=alice --passwd=pw1 --vc=none"
                )

            reactor.callInThread(thd)

        build = yield self.doForceBuild(
            wantSteps=True, triggerCallback=trigger_callback, wantLogs=True, wantProperties=True
        )
        self.assertEqual(build['buildid'], 1)
