"github.com/cloudfoundry/cf-acceptance-tests/helpers/assets"
)

var _ = AppsDescribe("An application that's already been pushed", func() {
	var appName string
	var persistentTestSetup *workflowhelpers.ReproducibleTestSuiteSetup

	BeforeEach(func() {
		persistentTestSetup = workflowhelpers.NewPersistentAppTestSuiteSetup(Config)
		persistentTestSetup.Setup()
	})

	AfterEach(func() {
		app_helpers.AppReport(appName, Config.DefaultTimeoutDuration())

		persistentTestSetup.Teardown()
	})

	BeforeEach(func() {
		appName = Config.GetPersistentAppHost()

		appQuery := cf.Cf("app", appName).Wait(Config.DefaultTimeoutDuration())
		// might exit with 1 or 0, depending on app status
		output := string(appQuery.Out.Contents())

		if appQuery.ExitCode() == 1 && strings.Contains(output, "not found") {
			pushCommand := cf.Cf("push", appName, "--no-start", "-b", Config.GetRubyBuildpackName(), "-m", DEFAULT_MEMORY_LIMIT, "-p", assets.NewAssets().Dora, "-d", Config.GetAppsDomain()).Wait(Config.DefaultTimeoutDuration())
			if pushCommand.ExitCode() != 0 {
				Expect(cf.Cf("delete", "-f", "-r", appName).Wait(Config.DefaultTimeoutDuration())).To(Exit(0))
				Fail("failed to create app")
			}
				"-p", assets.NewAssets().Binary,
				"--no-start",
				"-b", "binary_buildpack",
				"-m", DEFAULT_MEMORY_LIMIT,
				"-d", Config.GetAppsDomain(),
				"-c", "./app"),
				Config.CfPushTimeoutDuration()).Should(Exit(0))

			app_helpers.SetBackend(appName)
			Eventually(cf.Cf("start", appName), Config.CfPushTimeoutDuration()).Should(Exit(0))
		})

		AfterEach(func() {
			app_helpers.AppReport(appName, Config.DefaultTimeoutDuration())
			Eventually(cf.Cf("delete", appName, "-f"), Config.DefaultTimeoutDuration()).Should(Exit(0))

			runawayTestSetup.Teardown()
		})

		It("fails with insufficient resources", func() {
			scale := cf.Cf("scale", appName, "-m", workflowhelpers.RUNAWAY_QUOTA_MEM_LIMIT, "-f")
			Eventually(scale, Config.DefaultTimeoutDuration()).Should(Or(Say("insufficient"), Say("down")))
			scale.Kill()

			app := cf.Cf("app", appName)
			Eventually(app, Config.DefaultTimeoutDuration()).Should(Exit(0))
			Expect(app.Out).NotTo(Say("instances: 1/1"))
		})
	})
})