/**********************************************************************
 * do_chain.c  -- SS command for chaining two transactions
 * tty lucy client using SS library
 *
 * $Author: brlewis $
 * $Source: /afs/athena.mit.edu/astaff/project/lucydev/src/tty/do_chain.c,v $
 * $Header: /afs/athena.mit.edu/astaff/project/lucydev/src/tty/do_chain.c,v 1.1 91/09/24 14:43:05 brlewis Exp Locker: brlewis $
 *
 * Copyright 1991 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/
#include <mit-copyright.h>

#ifndef lint
static char rcsid_do_chain_c[] = "$Header: /afs/athena.mit.edu/astaff/project/lucydev/src/tty/do_chain.c,v 1.1 91/09/24 14:43:05 brlewis Exp Locker: brlewis $";
#endif /* lint */

#include <stdio.h>
#include <strings.h>
#include <ss/ss.h>
#include "lucy/lucy.h"
#include "config.h"

void
do_chain(argc, argv)
     int argc;
     char *argv[];
{
  long code;
  static int n1=0, n2=0, n3=0;
  ltrn *t2;

  /* do unchain */
  if (strcmp(argv[0], "unchain") == 0) {
    if (n2==0) {
      printf("Unchain works once after chain.\n");
      return;
    }
    if (code=luc_undelete(luv_curmtgp, n2)) {
      com_err(argv[0], code, "(%s)", luv_context);
      return;
    }
    if (code=luc_delete(luv_curmtgp, n3)) {
      com_err(argv[0], code, "(%s)", luv_context);
      return;
    }
    printf("Restored %d.\n", n2);
    return;
  }

  /* Check usage (chain n1 n2) */
  if (argc != 3 || !(n1=atoi(argv[1])) || !(n2=atoi(argv[2]))) {
    printf("Usage: %s number1 number2.\n", argv[0]);
    return;
  }

  /* swap them if they're in the wrong order */
  if (n1 > n2) {
    n3 = n1;
    n1 = n2;
    n2 = n3;
  }

  /* make sure n2 isn't already in a chain */
  if (code=luc_trn_info(luv_curmtgp, n2, &t2)) {
    com_err(argv[0], code, "(%s)", luv_context);
    return;
  }
  if (t2->lref != n2) {
    printf("Too late.  Transaction %d is already part of a chain.\n", n2);
    return;
  }

  /* call luc_chain */
  code = luc_chain(luv_curmtgp, n1, n2, &n3);
  if (code) com_err(argv[0], code, "(%s)", luv_context);
  else printf("Chained %d to %d.  The new number for %d is %d.\n",
	      n2, n1, n2, n3);

  return;
}
