/**
   * Changes the build result if baseline operation fails. (So cannot override {@linkplain
   * #needsToRunAfterFinalized()}).
   */
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws IOException, InterruptedException {
    Logger.debug("Invoking perform callout " + this.getClass().getName());
    long key = -1L;
    try {
      if (!(build.getProject().getScm() instanceof DimensionsSCM)) {
        final String message =
            "[DIMENSIONS] This plugin only works with the Dimensions SCM engine.";
        listener.fatalError(message);
        build.setResult(Result.FAILURE);
        throw new IOException(message);
      }
      // Create baseline if SUCCESS or UNSTABLE (could be just some Checkstyle violations).
      Result result = build.getResult();
      if (result != null && result.isBetterThan(Result.FAILURE)) {
        if (scm == null) {
          scm = (DimensionsSCM) build.getProject().getScm();
        }
        Logger.debug(
            "Dimensions user is "
                + scm.getJobUserName()
                + " , Dimensions installation is "
                + scm.getJobServer());
        key =
            scm.getAPI()
                .login(
                    scm.getJobUserName(),
                    scm.getJobPasswd(),
                    scm.getJobDatabase(),
                    scm.getJobServer(),
                    build);
        if (key > 0L) {
          VariableResolver<String> myResolver = build.getBuildVariableResolver();
          String requests = myResolver.resolve("DM_TARGET_REQUEST");
          String blnId = myResolver.resolve("DM_BASELINE");
          StringBuffer cblId = new StringBuffer();

          if (requests != null) {
            requests = requests.replaceAll(" ", "");
            requests = requests.toUpperCase(Values.ROOT_LOCALE);
          }

          if (blnScope != null && blnScope.length() > 0 && blnScope.equals("REVISED")) {
            if (requests == null
                || blnId == null
                || requests.length() == 0
                || blnId.length() == 0) {
              listener.fatalError(
                  "[DIMENSIONS] A revised baseline is only valid if you have specified DM_TARGET_REQUEST and DM_BASELINE.");
              build.setResult(Result.FAILURE);
              return false;
            }
          }

          {
            DimensionsResult res =
                scm.getAPI()
                    .createBaseline(
                        key,
                        scm.getProjectVersion(build, listener),
                        build,
                        blnScope,
                        blnTemplate,
                        blnOwningPart,
                        blnType,
                        requests,
                        blnId,
                        blnName,
                        cblId);
            if (res == null) {
              listener
                  .getLogger()
                  .println("[DIMENSIONS] The build failed to be tagged in Dimensions");
              listener.getLogger().flush();
              build.setResult(Result.FAILURE);
              canBaselineDeploy = canBaselineAction = canBaselineBuild = false;
            } else {
              listener
                  .getLogger()
                  .println(
                      "[DIMENSIONS] Build was successfully tagged in Dimensions as a baseline");
              listener
                  .getLogger()
                  .println(
                      "[DIMENSIONS] ("
                          + res.getMessage().replaceAll("\n", "\n[DIMENSIONS] ")
                          + ")");
              listener.getLogger().flush();
            }
          }
          if (canBaselineDeploy) {
            listener
                .getLogger()
                .println("[DIMENSIONS] Submitting a deployment job to Dimensions...");
            listener.getLogger().flush();
            DimensionsResult res =
                scm.getAPI()
                    .deployBaseline(
                        key,
                        scm.getProjectName(build, listener),
                        build,
                        deployState,
                        cblId.toString());
            if (res == null) {
              listener
                  .getLogger()
                  .println("[DIMENSIONS] The build baseline failed to be deployed in Dimensions");
              listener.getLogger().flush();
              build.setResult(Result.FAILURE);
              canBaselineDeploy = canBaselineAction = canBaselineBuild = false;
            } else {
              listener
                  .getLogger()
                  .println("[DIMENSIONS] Build baseline was successfully deployed in Dimensions");
              listener
                  .getLogger()
                  .println(
                      "[DIMENSIONS] ("
                          + res.getMessage().replaceAll("\n", "\n[DIMENSIONS] ")
                          + ")");
              listener.getLogger().flush();
            }
          }

          // This will active the build baseline functionality
          if (canBaselineBuild) {
            listener.getLogger().println("[DIMENSIONS] Submitting a build job to Dimensions...");
            listener.getLogger().flush();
            DimensionsResult res =
                scm.getAPI()
                    .buildBaseline(
                        key,
                        area,
                        scm.getProjectName(build, listener),
                        batch,
                        buildClean,
                        buildConfig,
                        buildOptions,
                        capture,
                        requests,
                        buildTargets,
                        build,
                        cblId.toString());
            if (res == null) {
              listener
                  .getLogger()
                  .println("[DIMENSIONS] The build baseline failed to be built in Dimensions");
              listener.getLogger().flush();
              build.setResult(Result.FAILURE);
              canBaselineDeploy = canBaselineAction = canBaselineBuild = false;
            } else {
              listener
                  .getLogger()
                  .println("[DIMENSIONS] Build baseline was successfully built in Dimensions");
              listener
                  .getLogger()
                  .println(
                      "[DIMENSIONS] ("
                          + res.getMessage().replaceAll("\n", "\n[DIMENSIONS] ")
                          + ")");
              listener.getLogger().flush();
            }
          }

          if (canBaselineAction) {
            listener
                .getLogger()
                .println("[DIMENSIONS] Actioning the build baseline in Dimensions...");
            listener.getLogger().flush();
            DimensionsResult res =
                scm.getAPI()
                    .actionBaseline(
                        key,
                        scm.getProjectName(build, listener),
                        build,
                        actionState,
                        cblId.toString());
            if (res == null) {
              listener
                  .getLogger()
                  .println("[DIMENSIONS] The build baseline failed to be actioned in Dimensions");
              build.setResult(Result.FAILURE);
              listener.getLogger().flush();
            } else {
              listener
                  .getLogger()
                  .println("[DIMENSIONS] Build baseline was successfully actioned in Dimensions");
              listener
                  .getLogger()
                  .println(
                      "[DIMENSIONS] ("
                          + res.getMessage().replaceAll("\n", "\n[DIMENSIONS] ")
                          + ")");
              listener.getLogger().flush();
            }
          }
        } else {
          listener.fatalError("[DIMENSIONS] Login to Dimensions failed.");
          build.setResult(Result.FAILURE);
          return false;
        }
      }
    } catch (Exception e) {
      String message =
          Values.exceptionMessage("Unable to tag build in Dimensions", e, "no message");
      listener.fatalError(message);
      Logger.debug(message, e);
      build.setResult(Result.FAILURE);
      return false;
    } finally {
      if (scm != null) {
        scm.getAPI().logout(key, build);
      }
    }
    return true;
  }