/* $Id: agentmisc.C,v 1.18 1999/11/28 04:19:07 dm Exp $ */

/*
 *
 * Copyright (C) 1998 David Mazieres (dm@uun.org)
 * Copyright (C) 1999 Michael Kaminsky (kaminsky@lcs.mit.edu)
 *
 * 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, 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 */

#include "agentmisc.h"
#include "crypt.h"
#include "rxx.h"

str dotsfs; 
str agentsock;

void
agent_setsock ()
{
  if (!dotsfs) {
    const char *home = getenv ("HOME");
    if (!home)
      fatal ("No HOME environment variable set\n");
    dotsfs = strbuf ("%s/.sfs", home);
  }
  if (!agentsock)
    if (char *p = getenv ("SFS_AGENTSOCK"))
      agentsock = p;
}

void
agent_ckdir ()
{
  if (!agentsock)
    agent_setsock ();
  if (!dotsfs)
    return;

  struct stat sb;
  if (stat (dotsfs, &sb) < 0)
    fatal ("%s: %m\n", dotsfs.cstr ());
  if (!S_ISDIR (sb.st_mode))
    fatal << dotsfs << ": not a directory\n";
  if (sb.st_mode & 077)
    fatal ("%s: mode 0%o should be 0700\n", dotsfs.cstr (), sb.st_mode & 0777);
}

void
agent_mkdir ()
{
  if (!agentsock)
    agent_setsock ();
  if (!dotsfs)
    return;

  struct stat sb;
  if (stat (dotsfs, &sb) < 0) {
    if (errno != ENOENT)
      fatal ("%s: %m\n", dotsfs.cstr ());
    warn << "creating directory " << dotsfs << "\n";
    if (mkdir (dotsfs, 0700) < 0 || stat (dotsfs, &sb) < 0)
      fatal ("%s: %m\n", dotsfs.cstr ());
  }
  if (!S_ISDIR (sb.st_mode))
    fatal << dotsfs << ": not a directory\n";
  if (sb.st_mode & 077)
    fatal ("%s: mode 0%o should be 0700\n", dotsfs.cstr (), sb.st_mode & 0777);
}

