/**
   * Create a package with the given name and add it to the given channel. If a package by that name
   * already exists, this simply returns that package.
   *
   * @param packageName The name of the package to create.
   * @param c The channel to which to add the package
   * @return The package with that name in the channel.
   * @throws Exception
   */
  public static Package addPackageToChannel(String packageName, Channel c) throws Exception {

    PackageName pn = PackageFactory.lookupOrCreatePackageByName(packageName);
    if (pn == null) {
      pn = PackageNameTest.createTestPackageName();
      pn.setName(packageName);
    }

    Long existingId = ChannelManager.getLatestPackageEqual(c.getId(), packageName);

    if (existingId != null) {
      return PackageFactory.lookupByIdAndOrg(existingId, c.getOrg());
    }

    // existingId =
    Session session = HibernateFactory.getSession();
    Query query =
        session.createQuery(
            "from Package as "
                + "package where package.org.id = "
                + c.getOrg().getId()
                + " and package.packageName.id = "
                + pn.getId());
    List packages = query.list();
    Package retval = null;
    if (packages != null && packages.size() > 0) {
      retval = (Package) packages.get(0);
    } else {
      retval = PackageTest.createTestPackage(c.getOrg());
    }

    retval.setPackageName(pn);
    TestUtils.saveAndFlush(retval);
    PackageTest.addPackageToChannelNewestPackage(retval, c);

    return retval;
  }