module Support
  class EntryPoint
    # Setting up the CI workspace:
    #   This should only run with `rake ci:init`, as some CI rake tasks use multiple cucumber rake tasks.
    #   logs - should all be cleared. Otherwise the cucumber-jvm-reports
    #     plugin will read files from previous builds.
    #   temp - should be cleared. These don't really matter; it just saves space.
    #   rerun.txt - should be deleted. Otherwise the task might not create a new rerun file properly.
    #   tmp/parallel_runtime_cucumber.log - should not be deleted. This is
    #     used by the parallel task to sort features by runtime.
    def setup_ci_workspace
      setup_single_workspace
      # create rerun file. not sure why this is necessary in this place.
      create_rerun_txt
      # make sure runtime dir exists, but don't clear it
      create File.join(Support::Paths.cucumber_root, "tmp")
    end

    # Setting up the local workspace:
    #  This only be run locally, as the CI method does this separately.
    #  logs - should all be cleared. These don't really matter; it just saves space.
    #  temp - should all be cleared. These don't really matter; it just saves space.
    def setup_single_workspace
      # clear out temp files to save space
      delete Paths.temp_root
      create Paths.temp_root
      # clear out logs -- otherwise old jsons get read by cucumber-jvm-reports
      delete Support::Paths.logs_root
      create Support::Paths.logs_root
    end

    private

    def create_rerun_txt
      path = File.join(Support::Paths.logs_root, "rerun.txt")
      File.open(path, "w+").close unless File.exist?(path)
    end

    # easier to mock in unit tests
    def create(dir)
      FileUtils.mkdir_p(dir)
    end

    def delete(dir)
      FileUtils.rm_rf(dir)
    end
  end
end
