/* $Id: syncdb.c,v 1.18 2002/07/21 13:23:36 richdawe Exp $ */

/*
 *  syncdb.c - Database synchronisation routines for pakke
 *  Copyright (C) 1999-2002 by Richard Dawe
 *      
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "common.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>

/* libpakke includes */
#include <libpakke/djgpp.h>
#include <libpakke/package.h>
#include <libpakke/packlist.h>
#include <libpakke/dsm.h>
#include <libpakke/mft.h>
#include <libpakke/log.h>
#include <libpakke/util.h>

#include "pakke.h"
#include "syncdb.h"
#include "md5hash.h"
#include "base64.h"
#include "misc.h"

/* We may want to install/upgrade the djgpp-dsms package, to get
 * a list of the latest available DJGPP packages. */
#include "mirror.h"
#include "wget.h"
#include "install.h"
#include "upgrade.h"

#ifdef HAVE_CONIO_H
#include <conio.h>
#else /* !HAVE_CONIO_H */
/* This hack needs testing! How do you flush input stream before read? */
#define getch getchar
#define putch putchar
#endif /* HAVE_CONIO_H */

static const char DJGPP_DSMS_PACKAGE[] = "djgpp-dsms";

/* Default DSMs for different platforms */
extern char *platform_dsm_table[];
extern char *platform_dsm_name_table[];

/* Forward declarations */
static int update_djgpp_dsms (PACKAGE_INFO *packages,
			      const PAKKE_SYNCDB *req_syncdb);

static int sync_from_manifests (const char *db_path,
				char **mft_path,
				char **dsm_path_avail,
				PACKAGE_INFO *mft_packages,
				PACKAGE_INFO *dsm_packages,
				PACKAGE_INFO *dsm_packages_avail);

static int update_dsms (const char *db_path,
			char **mft_path,
			char **dsm_path_avail,
			PACKAGE_INFO *dsm_packages,
			PACKAGE_INFO *dsm_packages_avail);

static int update_platform_dsms (const char *db_path,
				 PACKAGE_INFO *dsm_packages,
				 const int verbosity);

/* ------------------
 * - perform_syncdb -
 * ------------------ */

/*
 * TODO: Should this also detect when packages have been removed?
 * I think so.
 */

int
perform_syncdb (const PAKKE_SYNCDB *req)
{
  DSM_FILE_ERROR *dfe                = NULL;	/* DSM errors (main) */
  DSM_FILE_ERROR *dfe_avail          = NULL;	/* DSM errors (av.)  */
  PACKAGE_INFO   *package            = NULL;
  PACKAGE_INFO   *mft_packages       = NULL;
  PACKAGE_INFO   *dsm_packages       = NULL;
  PACKAGE_INFO   *dsm_packages_avail = NULL;
  int             count              = 0;
  char            db_path[PATH_MAX];

  /* Get the package descriptions */
  mft_packages = ver_load_all((const char **) req->mft_path, NULL);
  dsm_packages = dsm_load_all((const char **) req->dsm_path, NULL, &dfe);
	
  /* Display DSM errors. */
  if (dsm_file_errors_fatal(dfe))
    warn("Parsing failed for some DSM(s) in installed database");

  show_dsm_file_errors(dfe, req->verbosity);
  dsm_free_file_error_list(dfe);
  dfe = NULL;

  /* Check to see if we can install or upgrade the djgpp-dsms package
   * from one of the archive directories. */
  if (!update_djgpp_dsms(dsm_packages, req)) {
    /* Tidy up */
    packlist_free(mft_packages);
    packlist_free(dsm_packages);

    die("Unable to check for a new version of djgpp-dsms package!");
  }

  /* Regenerate package list from installed DSMs, because the DSM
   * for djgpp-dsms might have been updated by update_djgpp_dsms(). */
  packlist_free(dsm_packages);

  dsm_packages = dsm_load_all((const char **) req->dsm_path, NULL, &dfe);

  /* Display DSM errors. */
  if (dsm_file_errors_fatal(dfe))
    warn("Parsing failed for some DSM(s) in installed database");

  show_dsm_file_errors(dfe, req->verbosity);
  dsm_free_file_error_list(dfe);
  dfe = NULL;

  /* Load DSMs from the available packages database. Load also from
   * the manifest paths, to catch installed packages. */
  dsm_packages_avail = package
    = dsm_load_all((const char **) req->dsm_path_avail, NULL, &dfe_avail);

  if (package != NULL) {
    dsm_packages_avail = dsm_load_all((const char **) req->mft_path,
				      package, &dfe_avail);

    /* Tidy up original list in failure case. */
    if (dsm_packages_avail == NULL)
      packlist_free(package);

    package = NULL;
  }  

  /* Display DSM errors in available DSMs. */
  if (dsm_file_errors_fatal(dfe_avail))
    warn("Parsing failed for some DSM(s) in available database");

  show_dsm_file_errors(dfe_avail, req->verbosity);
  dsm_free_file_error_list(dfe_avail);
  dfe_avail = NULL;
	
  /* NB: dsm_packages == NULL is OK, because it means there are no
   * packages in the database yet. */
  if ((mft_packages == NULL) || (dsm_packages_avail == NULL)) {
    /* Tidy up */
    if (mft_packages != NULL)
      packlist_free(mft_packages);

    if (dsm_packages != NULL)
      packlist_free(dsm_packages);
    
    if (dsm_packages_avail != NULL)
      packlist_free(dsm_packages_avail);

    /* TODO: Error message */
    return(EXIT_FAILURE);
  }  
	
  /* Build the DSM database path */
  strcpy(db_path, req->root);
  addforwardslash(db_path);
  strcat(db_path, PAKKE_DB_PREFIX);
  addforwardslash(db_path);

  /* Are there any manifests to convert? */
  for (package = mft_packages;
       package != NULL;
       package = (PACKAGE_INFO *) package->q_forw) {
    if (strlen(package->name) > 0)
      count++;
  }

  if (count == 0) {
    info("No manifest-style packages need converting.\n");
  } else {
    /* Convert manifests */
    if (!sync_from_manifests(db_path, req->mft_path, req->dsm_path_avail,
			     mft_packages, dsm_packages, dsm_packages_avail)) {
      /* Tidy up */
      packlist_free(mft_packages);
      packlist_free(dsm_packages);
      packlist_free(dsm_packages_avail);

      die("Unable to create DSM(s) from manifest!");
    }
  }

  /* Update any installed DSMs */
  if (!update_dsms(db_path, req->mft_path, req->dsm_path_avail,
		   dsm_packages, dsm_packages_avail)) {
    /* Tidy up */
    packlist_free(mft_packages);
    packlist_free(dsm_packages);
    packlist_free(dsm_packages_avail);

    die("Unable to create/update DSM(s) for installed package(s)!");
  }

  /* Update any platform DSMs */
  if (!update_platform_dsms(db_path, dsm_packages, req->verbosity)) {
    /* Tidy up */
    packlist_free(mft_packages);
    packlist_free(dsm_packages);
    packlist_free(dsm_packages_avail);

    die("Unable to update platform DSM(s)!");
  }

  /* Regenerate package list from installed DSMs, because it might have
   * been updated by the above code. */
  packlist_free(dsm_packages);

  dsm_packages = dsm_load_all((const char **) req->dsm_path, NULL, &dfe);

  /* Display DSM errors. */
  if (dsm_file_errors_fatal(dfe))
    warn("Parsing failed for some DSM(s) in installed database");
		
  show_dsm_file_errors(dfe, req->verbosity);
  dsm_free_file_error_list(dfe);
  dfe = NULL;
	
  /* Create MD5 hashes of all files from a package, if necessary. */
  for (package = dsm_packages;
       package != NULL;
       package = (PACKAGE_INFO *) package->q_forw) {
    /* Skip virtual, group packages. */
    if (   (package->version.type == TYPE_NONE)
	|| (package->version.type == TYPE_VIRTUAL)
	|| (package->version.type == TYPE_GROUP))
      continue;

    /* TODO: This should use the package's prefix, not the global
     * root. */
    if (md5hash(package, db_path, req->root,
		(const char **) req->mft_path) == -1) {
      if (errno != EEXIST) {
	warnf("Error generating MD5 hashes for %s %s",
	      package->name, package_version_string(&package->version));
	perror("syncdb");
      }
    } else {
      printf(". Created MD5 hashes for files from %s %s\n",
	     package->name, package_version_string(&package->version));
    }
  }

  /* Free memory */
  packlist_free(dsm_packages);
  packlist_free(dsm_packages_avail);

  /* Always succeeds, unless something fatal happens. */
  return(EXIT_SUCCESS);
}

/* -----------------------
 * - download_djgpp_dsms -
 * ----------------------- */

static int
download_djgpp_dsms (const char *download_prefix, const int verbosity)
{
  char         v2_url[PATH_MAX];
  char         djgpp_dsms_url[PATH_MAX];
  char         destdir[PATH_MAX];
  char         olddir[PATH_MAX];
  const char  *mirror;
  char       **list;
  int          ret = 1; /* Succeed by default */
  int          i, j;

  /* Find which mirror to use. */
  mirror = mirror_mirror();
  if (mirror == NULL)
    return(0);

  /* Build the destination directory. */
  strcpy(destdir, download_prefix);
  addforwardslash(destdir);
  strcat(destdir, "v2/");

  /* Get a listing of v2/ on the mirror. */
  strcpy(v2_url, mirror);
  addforwardslash(v2_url);
  strcat(v2_url, "v2/");

  list = wget_get_listing(v2_url, verbosity);
  if (list == NULL)
    return(0);

  /* Save the current directory, then change into the destination directory,
   * to avoid the destination path getting too long. */
  if (getcwd(olddir, sizeof(olddir)) == NULL) {
    perror("pakke");
    return(0);
  }

  if (chdir(destdir) != 0) {
    perror("pakke");
    return(0);
  }

  /* Look for a matching file */
  for (i = 0; list[i] != NULL; i++) {
    int match = 1; /* Match by default */

    /* [dD][sS]\d{6}\.zip */
    if ((list[i][0] != 'd') && (list[i][0] != 'D')) {
      match = 0;
      continue;
    }

    if ((list[i][1] != 's') && (list[i][1] != 'S')) {
      match = 0;
      continue;
    }

    for (j = 2; j < 8; j++) {
      if (!isdigit(list[i][j])) {
	match = 0;
	break;
      }
    }

    if (!match)
      continue;

    if (strcasecmp(&list[i][8], ".zip") != 0) {
      match = 0;
      continue;
    }

    /* Build download URL */
    strcpy(djgpp_dsms_url, v2_url);
    addforwardslash(djgpp_dsms_url);
    strcat(djgpp_dsms_url, list[i]);

    if (!wget_get(djgpp_dsms_url, list[i], verbosity)) {
      /* TODO: Warning */
      ;
    }
  }

  if (chdir(olddir) != 0) {
    perror("pakke");
    ret = 0;
  }

  /* Tidy up */
  for (i = 0; list[i] != NULL; i++) { free(list[i]); }
  free(list);

  return(ret);
}

/* ---------------------
 * - update_djgpp_dsms -
 * --------------------- */

/*
 * The package 'djgpp-dsms' is a special package that is built by
 * the script 'scripts/pkgdsms.sh'. The package contains DSMs for all
 * the packages available from the DJGPP archive on Simtel.NET and
 * its mirrors. Every time a DJGPP package is uploaded to the archive,
 * the package is rebuilt.
 *
 * We can use install or upgrade to get the latest version of it. It's
 * version number contains the date, e.g. 2002.01.13.
 */

static int
update_djgpp_dsms (PACKAGE_INFO *packages, const PAKKE_SYNCDB *req_syncdb)
{
  PAKKE_INSTALL  req_install;
  PAKKE_UPGRADE  req_upgrade;
  PACKAGE_INFO  *package         = NULL;
  PACKAGE_INFO  *dd_package      = NULL; /* Current djgpp-dsms package */  
  PACKAGE_INFO  *new_dd_packages = NULL;
  PACKAGE_INFO  *new_dd_package  = NULL; /* Replacement djgpp-dsms package */
  DSM_ERROR     *de              = NULL;
  glob_t         glob_local;
  int            need_upgrade    = 0;
  int            keypress        = 0;
  int            ret             = 0;
  int            i;

  /*
   * Should we download package archives?
   *
   * -1 = an error occurred last time we tried to download or the user
   *      doesn't want to download;
   *  0 = haven't asked the user yet;
   *  1 = download.
   */
  int download = 0;

  for (package = packages; package != NULL; package = package->q_forw) {
    if (package_namecmp(package->name, DJGPP_DSMS_PACKAGE) == 0) {
      dd_package   = package;
      need_upgrade = 1;
      break;
    }
  }

  /* Try to get the latest djgpp-dsms from the web, if the user wishes to. */
  if ((download == 0) && (req_syncdb->download_prefix != NULL)) {
    printf("Try to download a newer version of %s - [y]es or [n]o? ",
	   DJGPP_DSMS_PACKAGE);

    if (req_syncdb->interactive) {
      /* Interactive */
      keypress = 0;
      while (keypress == 0) {
	keypress = getch();

	switch(keypress) {
	case 'y': case 'Y':
	  download = 1;
	  break;

	case 'n': case 'N':
	  download = -1; /* Don't ask again */
	  break;

	default:
	  putch('\a');
	  keypress = 0;
	  break;
	}
      }
    } else {
      /* Non-interactive => don't download anything */
      keypress = 'n';
    }

    printf("%c\n", keypress);
  }

  /* Do the download */
  if (   (download == 1)
      && !download_djgpp_dsms(req_syncdb->download_prefix,
			      req_syncdb->verbosity)) {
    /* TODO: Error */
    ;
  }

  /* Find the djgpp-dsms package in the ZIP paths. */
  if (glob_in_paths_with_suffixes("ds*.zip",
				  (const char **) req_syncdb->zip_path,
				  djgpp_archive_prefixes,
				  0, NULL, &glob_local)) {
    /* TODO: Error */
    ;
  }

  /* Parse the DSMs of the djgpp-dsm packages, so we can get the latest. */
  for (i = 0; i < glob_local.gl_pathc; i++) {
    new_dd_package = malloc(sizeof(*new_dd_package));
    if (new_dd_package == NULL) {
      /* TODO: Warning? */
      break;
    }

    if (new_dd_packages == NULL)
      new_dd_packages = new_dd_package;
    else
      packlist_add(new_dd_packages, new_dd_package);

    if (   dsm_get_and_parse(glob_local.gl_pathv[i], new_dd_package, NULL, &de)
	!= DSM_OK) {
      /* If there were any parsing errors, display them. */
      show_dsm_errors(glob_local.gl_pathv[i], de, req_syncdb->verbosity);
      dsm_free_error_list(de);
      de = NULL;
    } else {
      /* Store the package's archive filename. */
      strcpy(new_dd_package->path, glob_local.gl_pathv[i]);
    }
  }

  globfree(&glob_local);

  /* Nothing to do, so just return. */
  if (new_dd_packages == NULL)
    return(1);

  /* Do we have the current version? If so, nothing to do. */
  if (   (dd_package != NULL)
      && (package_vercmp(&dd_package->version,
			 &new_dd_package->version) >= 0)) {
    /* TODO: Verbosity level? */
    infof("No later version of %s package found", DJGPP_DSMS_PACKAGE);

    infof("Current is %s %s",
	  dd_package->name,
	  package_version_string(&dd_package->version));

    infof("Found %s %s",
	  new_dd_package->name,
	  package_version_string(&new_dd_package->version));

    /* Tidy up */
    packlist_free(new_dd_packages);

    return(1);
  }

  /* Install/upgrade djgpp-dsms */
  if (!need_upgrade) {
    /* Install djggp-dsms */
    req_install.op             = OP_INSTALL;
    req_install.mod            = IM_NONE;
    req_install.verbosity      = req_syncdb->verbosity;
    req_install.root           = req_syncdb->root;
    req_install.prefix         = req_syncdb->prefix;
    req_install.backup_prefix  = req_syncdb->backup_prefix;
    req_install.name           = new_dd_package->path;
    req_install.dsm_path       = req_syncdb->dsm_path;
    req_install.mft_path       = req_syncdb->mft_path;
    req_install.dsm_path_avail = NULL;
    req_install.zip_path       = req_syncdb->zip_path;
    req_install.tar_gzip_path  = req_syncdb->tar_gzip_path;
    req_install.tar_bzip2_path = req_syncdb->tar_bzip2_path;

    ret = perform_install(&req_install);
  } else {
    /* Upgrade djggp-dsms */
    req_upgrade.op             = OP_UPGRADE;
    req_upgrade.mod            = UPM_NONE;
    req_upgrade.verbosity      = req_syncdb->verbosity;
    req_upgrade.root           = req_syncdb->root;
    req_upgrade.prefix         = req_syncdb->prefix;
    req_upgrade.backup_prefix  = req_syncdb->backup_prefix;
    req_upgrade.name           = new_dd_package->path;
    req_upgrade.dsm_path       = req_syncdb->dsm_path;
    req_upgrade.mft_path       = req_syncdb->mft_path;
    /*req_upgrade.dsm_path_avail = NULL;*/
    req_upgrade.zip_path       = req_syncdb->zip_path;
    req_upgrade.tar_gzip_path  = req_syncdb->tar_gzip_path;
    req_upgrade.tar_bzip2_path = req_syncdb->tar_bzip2_path;

    ret = perform_upgrade(&req_upgrade);
  }

  /* Tidy up */
  packlist_free(new_dd_packages);

  return(ret == EXIT_SUCCESS ? 1 : 0);
}

/* -----------------------
 * - sync_from_manifests -
 * ----------------------- */

static int
sync_from_manifests (const char *db_path,
		     char **mft_path,
		     char **dsm_path_avail,
		     PACKAGE_INFO *mft_packages,
		     PACKAGE_INFO *dsm_packages,
		     PACKAGE_INFO *dsm_packages_avail)
{
  PACKAGE_INFO *package  = NULL;
  PACKAGE_INFO *package2 = NULL;
  char         *dsm      = NULL; /* DSM text */
  char         *dsm_file = NULL;
  FILE         *fp       = NULL;
  char          new_dsm_file[PATH_MAX];
  char          temp_file[PATH_MAX];
  int           found    = 0;

  /* Go through manifest list and look for matching DSMs. */
  for (package = mft_packages;
       package != NULL;
       package = (PACKAGE_INFO *) package->q_forw) {
    found = 0;

    /* Skip already installed DSMs. Normally a package list would
     * not include duplicates, because we would have run
     * packlist_dedupe() on it, but here it's all under our
     * control. */
    for (package2 = dsm_packages;
	 package2 != NULL;
	 package2 = (PACKAGE_INFO *) package2->q_forw) {
      if (strlen(package2->name) == 0) continue;

      if (strcasecmp(package->manifest, package2->manifest) == 0) {
	found = 1;
	break;
      }
    }

    if (found)
      continue;

    /* Available DSMs */
    for (package2 = dsm_packages_avail;
	 package2 != NULL;
	 package2 = (PACKAGE_INFO *) package2->q_forw) {
      if (strcasecmp(package->manifest, package2->manifest) == 0) {
	found = 1;

	/* Status message */
	printf(". Matched package: %s -> %s %s\n",
	       package->name,
	       package2->name,
	       package_version_string(&package2->version));

	break;
      }
    }

    if (!found) {
      /* Failed to match - move onto next */
      warnf("Unmatched package: '%s'", package->name);
      continue;
    }

    /* For the matched manifest -> DSM mapping, copy the DSM to
     * the DSM database. Find the DSM case insensitively. */
    strcpy(temp_file, package2->dsm_name);
    strcat(temp_file, ".dsm");

    dsm_file = find_in_paths(temp_file, (const char **) dsm_path_avail, 0);

    if (dsm_file == NULL) {
      /* Look in the manifest directory too */
      dsm_file = find_in_paths(temp_file, (const char **) mft_path, 0);
    }

    if (dsm_file == NULL) {
      warnf("Unable to find DSM file '%s'", temp_file);
      continue;
    }

    dsm = read_text_file_to_memory(dsm_file);

    if (dsm == NULL) {
      warnf("Unable to read DSM file '%s'", dsm_file);
      continue;
    }

    strcpy(new_dsm_file, db_path);
    strcat(new_dsm_file, temp_file);

    fp = fopen(new_dsm_file, "wt");
    if (fp == NULL) {
      free(dsm);
      packlist_free(mft_packages);
      packlist_free(dsm_packages);
      packlist_free(dsm_packages_avail);
      die("Unable to create DSM for installed package!");
    }

    if (fwrite(dsm, strlen(dsm), 1, fp) <= 0) {
      free(dsm);
      packlist_free(mft_packages);
      packlist_free(dsm_packages);
      packlist_free(dsm_packages_avail);
      die("Unable to write DSM for installed package!");
    }

    free(dsm);
    fclose(fp);

    printf(". Created DSM for %s %s\n",
	   package2->name, package_version_string(&package2->version));
  }

  return(1);
}

/* ---------------
 * - update_dsms -
 * --------------- */

static int
update_dsms (const char *db_path,
	     char **mft_path,
	     char **dsm_path_avail,
	     PACKAGE_INFO *dsm_packages,
	     PACKAGE_INFO *dsm_packages_avail)
{
  PACKAGE_INFO *package  = NULL;
  PACKAGE_INFO *package2 = NULL;
  char         *dsm      = NULL; /* DSM text */
  char         *dsm_file = NULL;
  FILE         *fp       = NULL;
  char new_dsm_file[PATH_MAX];
  char temp_file[PATH_MAX];
  int found = 0;

  /* Go through the installed DSM list and see if any of the DSMs have
   * been updated. */
  for (package = dsm_packages;
       package != NULL;
       package = (PACKAGE_INFO *) package->q_forw) {
    /* Compare with entried from available DSM list. */
    found = 0;
		
    for (package2 = dsm_packages_avail;
	 package2 != NULL;
	 package2 = (PACKAGE_INFO *) package2->q_forw) {
      /* Comparison on names */
      if (package_namecmp(package->name, package2->name) != 0)
	continue;

      /* Version comparison */
      if (package_vercmp(&package->version, &package2->version) != 0)
	continue;

      /* DSM file version */
      if (package_vercmp(&package->dsm_file_version,
			 &package2->dsm_file_version) >= 0) {
	/* We have the same or an older DSM version,
	 * so continue searching. */
	/* TODO: Should this abort here? Does the
	 * package list take dsm-file-version into
	 * account? */
	continue;
      }

      /* Set found flag, so DSM will get updated. */
      found = 1;
      break;
    }

    if (!found)
      continue;

    /* For the matched DSM, copy the new DSM to the DSM database.
     * Find the DSM case insensitively. */
		
    /* TODO: This code assumes the dsm-name has not changed between
     * versions of the dsm-file. Is this a reasonable
     * restriction? */
    strcpy(temp_file, package2->dsm_name);
    strcat(temp_file, ".dsm");
    dsm_file = find_in_paths(temp_file, (const char **) dsm_path_avail, 0);

    if (dsm_file == NULL) {
      /* Look in the manifest directory too */
      dsm_file = find_in_paths(temp_file, (const char **) mft_path, 0);
    }

    if (dsm_file == NULL) {
      warnf("Unable to find DSM file '%s'", temp_file);
      continue;
    }

    dsm = read_text_file_to_memory(dsm_file);

    if (dsm == NULL) {
      warnf("Unable to read DSM file '%s'", dsm_file);
      continue;
    }

    strcpy(new_dsm_file, db_path);
    strcat(new_dsm_file, temp_file);

    /* Write out the DSM. */
    fp = fopen(new_dsm_file, "wt");
    if (fp == NULL) {
      free(dsm);
      return(0);      
    }

    if (fwrite(dsm, strlen(dsm), 1, fp) <= 0) {
      free(dsm);
      return(0);
    }

    free(dsm);
    fclose(fp);

    printf(". Updated DSM for %s %s\n",
	   package2->name, package_version_string(&package2->version));
  }

  return(1);
}

/* ------------------------
 * - update_platform_dsms -
 * ------------------------ */

static int
update_platform_dsms (const char *db_path,
		      PACKAGE_INFO *dsm_packages,
		      const int verbosity)
{
  PACKAGE_INFO *package = NULL;
  PACKAGE_INFO  plat_package; /* Parsed platform DSM */
  DSM_ERROR    *de      = NULL;
  char          path[PATH_MAX];
  FILE         *fp      = NULL;
  int           found   = 0;
  int           i, ret;

  for (i = 0; platform_dsm_table[i] != NULL; i++) {
    assert(platform_dsm_name_table[i] != NULL);

    /* Parse the platform DSM, so we can do version comparisons with
     * the installed package database. */
    ret = dsm_parse(platform_dsm_table[i], &plat_package, &de);

    if (ret != DSM_OK) {
      warnf("Parsing failed for platform DSM '%s'",
	    platform_dsm_name_table[i]);
    }

    /* Display parsing errors, if any. */
    if (de) {
      show_dsm_errors(platform_dsm_name_table[i], de, verbosity);
      dsm_free_error_list(de);
      de = NULL;
    }

    if (ret != DSM_OK) {
      warnf("Platform DSM '%s' skipped", platform_dsm_name_table[i]); 
      continue;
    }

    /* Check each installed package */
    for (found = 0, package = dsm_packages;
	 package != NULL;
	 package = package->q_forw) {
      /* Match on name and version */
      if (package_namecmp(package->name, plat_package.name) != 0)
	continue;

      if (package_vercmp(&package->version, &plat_package.version) != 0)
	continue;

      if (package_vercmp(&package->dsm_file_version,
			 &plat_package.dsm_file_version) >= 0)
	continue;

      /* Matched */
      found = 1;
      break;
    }

    if (found) {
      /* Update the platform DSM */
      printf(". Updating platform DSM for %s %s\n",
	   plat_package.name, package_version_string(&plat_package.version));

      strcpy(path, db_path);
      strcat(path, platform_dsm_name_table[i]);
      strcat(path, ".dsm");

      fp = fopen(path, "wt");
      if (fp == NULL) {
	warnf("Unable to write DSM for platform '%s'!",
	      platform_dsm_name_table[i]);
      } else {
	/* Write new DSM */
	fputs(platform_dsm_table[i], fp);
	fclose(fp);
      }
    }
  }

  return(1);
}
