/***********************************************************
        Copyright 1991,1994 by Carnegie Mellon University

                      All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of CMU not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.

CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
******************************************************************/
#include "depotlib.h"

#ifdef HAVE_AFS

#ifndef SABER
#ifndef LINT
static char rcs_id[]="$Id: AndrewFileSystem.c,v 1.6 1995/04/27 14:06:37 ww0r Exp $";
#endif /* LINT */
#endif /* SABER */

/*
 * Author: Sohan C. Ramakrishna Pillai
 *	   Modified by Walter Wong
d */

#include <afs/param.h>
#include <afs/stds.h>
#include <rx/xdr.h>
#ifdef AFS_SUN5_ENV
#include <sys/ioccom.h>
#endif
#include <sys/ioctl.h>
#include <afs/cellconfig.h>
#include <afs/vice.h>
#include <afs/venus.h>
#include <afs/vlserver.h>
#include <afs/afsint.h>
#include <afs/volser.h>
#include <afs/volint.h>
#include <afs/vldbint.h>
#include <ubik.h>


#include "util.h"
#include "DepotErrorCodes.h"
#include "FileSystem.h"
#include "AndrewFileSystem.h"

#define MAXSIZE 2*BUFSIZ

static volintInfo *AFS_vol_GetInfobyID();
static int GetServerAndPart();

static struct ubik_client *cstruct;
static struct rx_securityClass *sc;
static int securityindex = 0;
#define UV_BIND(s, p) rx_NewConnection((s), htons(p), VOLSERVICE_ID,sc,securityindex)


static int
GetServerAndPart(entry, voltype, server, part)
     struct vldbentry entry;
     long voltype, *server, *part;
{
  int i;

  *server = -1;
  *part = -1;
  if ((voltype == RWVOL) || (voltype  == BACKVOL)) {
    for (i = 0; i < entry.nServers ; i++){
      if (entry.serverFlags[i] & ITSRWVOL){
	*server = entry.serverNumber[i];
	*part = entry.serverPartition[i];
        return(1);
      }
    }
  }
  if (voltype == ROVOL) {
    for (i = 0; i < entry.nServers ; i++) {
      if ((entry.serverFlags[i] & ITSROVOL)) {
	*server = entry.serverNumber[i];
	*part = entry.serverPartition[i];
	return(1);
      }
    }
  }
  return(-1);
}

/* return of NULL  means there is an error somewhere
 * returns volinfoInfo, this needs to be freed when done
 */
static volintInfo *
AFS_vol_GetInfobyID(volid)
     long volid;
{
  static volintInfo *volinfo;
  struct vldbentry entry;
  long code;
  int voltype;
  long aserver,apart;
  extern int VL_GetEntryByID();
  char volbusy;
  struct rx_connection *aconn;
  
  code = ubik_Call(VL_GetEntryByID, cstruct, 0, volid,-1, &entry);
  if (code) {
    FatalError(E_AFSPROBLEM, "Could not get the VLDB entry for %d\n", volid);
  }
  MapHostToNetwork(&entry);
  if (entry.volumeId[RWVOL] == volid) {
    voltype = RWVOL;
  } else if (entry.volumeId[ROVOL] == volid) {
    voltype = ROVOL;
  } else  if (entry.volumeId[BACKVOL] == volid) {
    voltype = BACKVOL;
  }
    
  GetServerAndPart(entry, voltype, &aserver,&apart);
  if ((voltype == RWVOL) &&(aserver == -1 || apart == -1)) {
    FatalError(E_AFSPROBLEM,
	       "Could not find volume (%d) on any servers\n", volid);
  }
  volbusy = 1;
  aconn = UV_BIND(aserver,AFSCONF_VOLUMEPORT);

  while (volbusy) {
    volEntries volumeInfo;

    volumeInfo.volEntries_val = (volintInfo *)0;/*this hints the stub to allocated */
    volumeInfo.volEntries_len = 0;
    
    if (AFSVolListOneVolume(aconn, apart, volid, &volumeInfo)) {
      FatalError(E_AFSPROBLEM,
		 "Unable to get info on %d, code = %d\n", volid, code);
    }
    volinfo = volumeInfo.volEntries_val;
    volbusy = (volinfo->status == VBUSY);
    if (volbusy) {
      fprintf(stderr,"** Waiting for busy volume %d **\n", volinfo->volid);
      (void)sleep(5);
    }
  }
  if (aconn)
    rx_DestroyConnection(aconn);

  return(volinfo);
}

int
AFS_vol_init()
{
  struct afsconf_cell info;
  struct afsconf_dir *tdir;
  static struct rx_connection *serverconns[VLDB_MAXSERVERS];
  long i;

  if (rx_Init(0))
    return(-1);
/*  rx_SetRxDeadTime(50); */
  if ((tdir = afsconf_Open(AFSCONF_CLIENTNAME)) == (struct afsconf_dir *) NULL) {
    return(-2);
  }
  if (afsconf_GetCellInfo(tdir, NULL, AFSCONF_VLDBSERVICE, &info)) {
    return(-3);
  }
  if (info.numServers > VLDB_MAXSERVERS) { 
    return(-4);
  }
  sc = (struct rx_securityClass *)rxnull_NewClientSecurityObject();
  for (i = 0;i<info.numServers;i++)
    serverconns[i] = rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
				      info.hostAddr[i].sin_port,
				      USER_SERVICE_ID, 
				      sc, securityindex);
  if (ubik_ClientInit(serverconns, &cstruct)) {
    return(-5);
  }

  return(0);
}

int
AFS_vol_done()
{
  rx_Finalize();
  return 0;
}

/*
 * Gets AFS volume info for fsinfop->path.
 * CAVEAT:
 * fsinfop->fs_id should have enough space to hold the filesystemid.
 */
int AFS_GetVolumeInfo(fsinfop)
     FSINFO *fsinfop;
{
  char buf[MAXSIZE];
  register long code;
  struct ViceIoctl blob;
  struct VolumeStatus *status;
  volintInfo *volinfo;

  blob.out_size = MAXSIZE;
  blob.in_size = 0;
  blob.out = buf;
  code = pioctl(fsinfop->path, VIOCGETVOLSTAT, &blob, 1);
  if (code)
    {
      /* Not an AFS thingie */
      fsinfop->fs_id[0] = '\0'; fsinfop->fs_modtime = 0;
    }
  else
    {
      status = (VolumeStatus *)buf;
      (void)sprintf(fsinfop->fs_id, "AFS:%d", status->Vid);
      volinfo = AFS_vol_GetInfobyID(status->Vid);
      fsinfop->fs_modtime = volinfo->updateDate;
      free(volinfo);
    }

  return 0;
}
#endif /* HAVE_AFS */
/* $Source: /afs/andrew.cmu.edu/system/src/local/depot2/022/src/lib/FileSystemUtil/RCS/AndrewFileSystem.c,v $ */
