/*
 * pinit.c
 *
 * Initialize the master and drive keys.
 *
 * Author: Howard Gobioff
 */
/*
 * Copyright (c) of Carnegie Mellon University, 1997,1998,1999.
 *
 * Permission to reproduce, use, and prepare derivative works of
 * this software for internal use is granted provided the copyright
 * and "No Warranty" statements are included with all reproductions
 * and derivative works. This software may also be redistributed
 * without charge provided that the copyright and "No Warranty"
 * statements are included in all redistributions.
 *
 * NO WARRANTY. THIS SOFTWARE IS FURNISHED ON AN "AS IS" BASIS.
 * CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER
 * EXPRESSED OR IMPLIED AS TO THE MATTER INCLUDING, BUT NOT LIMITED
 * TO: WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY
 * OF RESULTS OR RESULTS OBTAINED FROM USE OF THIS SOFTWARE. CARNEGIE
 * MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT
 * TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.
 */


#include <nasd/nasd_options.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <nasd/nasd_pdrive.h>
#include <nasd/nasd_pdrive_client.h>

nasd_error_string_t error_text;

void
usage()
{
  fprintf(stderr, "USAGE: pinit servername master_password\n");
  fflush(stderr);
  exit(1);
}

int
main(argc, argv)
  int     argc;
  char  **argv;
{
  nasd_p_initialize_dr_args_t args;
  nasd_p_initialize_dr_res_t res;
  nasd_drive_handle_t h;
  nasd_rpc_status_t status;
  nasd_sec_keyring_t keys;
  char *server_name;
  nasd_status_t rc;

  if (argc != 3)
    usage();

  server_name = argv[1];
  
  rc = nasd_cl_p_init();
  if (rc) {
    fprintf(stderr,
      "ERROR: cannot initialize client library, error 0x%x (%s)\n",
      rc, nasd_error_string(rc));
    fflush(stderr);
    exit(1);
  }

  rc = nasd_bind_to_drive(server_name, NASD_PDRIVE_PORT,
    NASD_BIND_DEFAULT, NULL, 0, &h);
  if (rc) {
    fprintf(stderr, "ERROR: cannot bind to server %s error 0x%x (%s)\n",
      server_name, rc, nasd_error_string(rc));
    fflush(stderr);
    exit(1);
  }

  nasd_sec_password_to_keys(argv[2], 0, &keys);
  bcopy(keys.master_key, args.in_master_key, sizeof(nasd_key_t));
  bcopy(keys.drive_key, args.in_drive_key, sizeof(nasd_key_t));
  bzero((char *)&res, sizeof(nasd_p_initialize_dr_res_t));
  nasd_cl_p_initialize_dr(h, &args, &res, &status);

  if (res.nasd_status || status) {
    fprintf(stderr, "ERROR: nasd_status 0x%x (%s) status 0x%x (%s)\n",
      res.nasd_status, nasd_error_string(res.nasd_status),
      status, nasd_cl_error_string(h, status, error_text));
    exit(2);
  }

  printf("Succeeded\n");
  fflush(stdout);

  rc = nasd_unbind_drive(&h);
  if (rc) {
    fprintf(stderr, "ERROR: got 0x%x (%s) from nasd_unbind_drive()\n",
      rc, nasd_error_string(rc));
    fflush(stderr);
    exit(2);
  }

  nasd_cl_p_shutdown();

  exit(0);
}

