/**
   * Get the id of the Package installed for this KS. Here we'll verify that the kickstart package
   * exists in the host server's tools channel. The host server will need it to perform necessary
   * actions on either itself or the target system (if different).
   *
   * @return Long id of Package used for this KS.
   */
  public ValidatorError validateKickstartPackage() {
    if (cobblerOnly) {
      return null;
    }

    Server hostServer = getHostServer();
    Set<Long> serverChannelIds = new HashSet<Long>();
    Iterator<Channel> i = hostServer.getChannels().iterator();
    while (i.hasNext()) {
      Channel c = i.next();
      serverChannelIds.add(c.getId());
    }

    // check for package among channels the server is subscribed to.
    // If one is found, return
    Map<String, Long> pkgToInstall = findKickstartPackageToInstall(hostServer, serverChannelIds);
    if (pkgToInstall != null) {
      this.packagesToInstall.add(pkgToInstall);
      log.debug("    packagesToInstall: " + packagesToInstall);
      return null;
    }

    // otherwise search in channels that can be subscribed.
    // If one is found, subscribe channel and return
    Set<Long> subscribableChannelIds =
        SystemManager.subscribableChannelIds(
            hostServer.getId(), this.user.getId(), hostServer.getBaseChannel().getId());
    pkgToInstall = findKickstartPackageToInstall(hostServer, subscribableChannelIds);

    if (pkgToInstall != null) {
      this.packagesToInstall.add(pkgToInstall);
      log.debug("    packagesToInstall: " + packagesToInstall);
      Long cid = pkgToInstall.get("channel_id");
      log.debug("    Subscribing to: " + cid);
      Channel c = ChannelFactory.lookupById(cid);
      try {
        SystemManager.subscribeServerToChannel(this.user, server, c);
        log.debug("    Subscribed: " + cid);
      } catch (PermissionException pe) {
        return new ValidatorError("kickstart.schedule.cantsubscribe");
      } catch (Exception e) {
        return new ValidatorError(
            "kickstart.schedule.cantsubscribe.channel", c.getName(), server.getName());
      }
      return null;
    }

    return new ValidatorError(
        "kickstart.schedule.nopackage", this.getKsdata().getChannel().getName());
  }
  /**
   * Do the validation needed for this command. This ensures that the system hosting the kickstart
   * has the necessary resources to do so.
   *
   * @return Returns a ValidatorError, if any errors occur
   */
  public ValidatorError doValidation() {
    ValidatorError error = validateNetworkInterface();
    if (error != null) {
      return error;
    }
    if (isCobblerOnly()) {
      return null;
    }
    Server hostServer = getHostServer();

    // Check base channel.
    log.debug("** Checking basechannel.");
    if (hostServer.getBaseChannel() == null) {
      return new ValidatorError("kickstart.schedule.nobasechannel", hostServer.getName());
    }

    // Check that we have a valid ks package
    log.debug("** Checking validkspackage");
    error = validateKickstartPackage();
    if (error != null) {
      return error;
    }

    if (ksdata.isRhel()) {
      // Check that we have a valid up2date version
      log.debug("** Checking valid up2date");
      error = validateUp2dateVersion();
      if (error != null) {
        return error;
      }
    }

    // we already shall be subscribed to the tools channel
    // (since validateKickstartPackage), so no other actions needed
    return null;
  }
  private Profile processProfileType(String profileTypeIn) {
    log.debug("PROFILE_TYPE=" + profileTypeIn);

    if (profileTypeIn == null
        || profileTypeIn.length() == 0
        || // TODO: fix this hack
        profileTypeIn.equals(TARGET_PROFILE_TYPE_NONE)) {
      return null;
    }
    Profile retval = null;
    // Profile of this existing system's packages
    String pname =
        LocalizationService.getInstance()
            .getMessage("kickstart.session.newprofile", this.kickstartSession.getId().toString());
    if (profileTypeIn.equals(TARGET_PROFILE_TYPE_EXISTING)) {
      log.debug("    TARGET_PROFILE_TYPE_EXISTING");
      // "Profile for kickstart session "
      retval =
          ProfileManager.createProfile(
              ProfileFactory.TYPE_SYNC_PROFILE,
              this.user,
              getTargetServer().getBaseChannel(),
              pname,
              pname);
      ProfileManager.copyFrom(this.server, retval);
    }
    // Profile of 'stored profile'
    else if (profileTypeIn.equals(TARGET_PROFILE_TYPE_PACKAGE)) {
      log.debug("    TARGET_PROFILE_TYPE_PACKAGE");
      if (this.profileId == null) {
        throw new UnsupportedOperationException(
            "You specified a target profile type"
                + TARGET_PROFILE_TYPE_PACKAGE
                + " but this.profileId is null");
      }
      retval = ProfileManager.lookupByIdAndOrg(this.profileId, this.user.getOrg());
    }
    // Some other system's profile
    else if (profileTypeIn.equals(TARGET_PROFILE_TYPE_SYSTEM)) {
      Server otherServer = ServerFactory.lookupById(this.serverProfileId);
      log.debug("    TARGET_PROFILE_TYPE_SYSTEM");
      log.debug("    this.serverProfileId      : " + this.serverProfileId);
      log.debug("    otherServer               : " + otherServer);
      if (otherServer != null) {
        log.debug("otherServer.Id            : " + otherServer.getId());
        log.debug("otherServer.getBaseChannel: " + otherServer.getBaseChannel());
      }

      retval =
          ProfileManager.createProfile(
              ProfileFactory.TYPE_SYNC_PROFILE,
              this.user,
              otherServer.getBaseChannel(),
              pname,
              pname);
      ProfileManager.copyFrom(otherServer, retval);
    }
    this.kickstartSession.setServerProfile(retval);
    KickstartFactory.saveKickstartSession(this.kickstartSession);

    if (getTargetServer() != null) {
      HibernateFactory.getSession().refresh(getTargetServer());
    }

    // TODO: Compute missing packages and forward user to the missing page

    return retval;
  }
  /**
   * Looks up a list of applicable kickstart profiles. The list is generated based on matches
   * between the server's base channel arch and the profile's channel arch
   *
   * @return DataResult, else null if the server does not exist or does not have a base channel
   *     assigned
   */
  public DataResult<KickstartDto> getKickstartProfiles() {
    log.debug("getKickstartProfiles()");
    DataResult<KickstartDto> retval = new DataResult<KickstartDto>(Collections.EMPTY_LIST);

    // Profiles are associated with the host; the target system might not be created
    // yet.  Also, the host will be the one performing the kickstart, so the profile
    // is relative to that system.

    Server hostServer = getHostServer();
    if (hostServer != null) {
      log.debug("getKickstartProfiles(): hostServer isnt null");
      Channel baseChannel = hostServer.getBaseChannel();
      if (baseChannel != null) {
        log.debug("getKickstartProfiles(): hostServer.baseChannel isnt null");
        ChannelArch arch = baseChannel.getChannelArch();
        SelectMode mode = getMode();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("org_id", this.user.getOrg().getId());
        params.put("prim_arch_id", arch.getId());
        if (arch.getName().equals("x86_64")) {
          log.debug("    Adding IA-32 to search list.");
          ChannelArch ia32arch = ChannelFactory.lookupArchByName("IA-32");
          params.put("sec_arch_id", ia32arch.getId());
        } else if (arch.getName().equals("IA-32")
            && (hostServer.getServerArch().getName().equals(ServerConstants.getArchI686().getName())
                || hostServer
                    .getServerArch()
                    .getName()
                    .equals(ServerConstants.getArchATHLON().getName()))) {
          log.debug("    Adding x86_64 to search list.");
          ChannelArch x86Arch = ChannelFactory.lookupArchByName("x86_64");
          params.put("sec_arch_id", x86Arch.getId());
        } else if (arch.getName().equals("PPC")) {
          log.debug("    Adding ppc64le to search list.");
          ChannelArch ppc64le = ChannelFactory.lookupArchByName("PPC64LE");
          params.put("sec_arch_id", ppc64le.getId());
        } else if (arch.getName().equals("PPC64LE")) {
          log.debug("    Adding ppc to search list.");
          ChannelArch ppc = ChannelFactory.lookupArchByName("PPC");
          params.put("sec_arch_id", ppc.getId());
        } else {
          params.put("sec_arch_id", arch.getId());
        }
        retval = mode.execute(params);
        if (log.isDebugEnabled()) {
          log.debug("got back from DB: " + retval);
        }
        KickstartLister.getInstance().setKickstartUrls(retval, user);
        KickstartLister.getInstance().pruneInvalid(user, retval);
        retval.setTotalSize(retval.size());
      }
    }

    List<CobblerProfileDto> dtos = KickstartLister.getInstance().listCobblerProfiles(user);
    if (log.isDebugEnabled()) {
      log.debug("got back from cobbler: " + dtos);
    }
    retval.setTotalSize(retval.getTotalSize() + dtos.size());
    retval.addAll(dtos);

    return retval;
  }