/* 
 * $Id: pcfs.c,v 1.6 1993/10/29 16:59:52 ejb Exp $
 * $Source: /home/ejb/source/util/work/RCS/pcfs.c,v $
 * $Author: ejb $
 *
 * This is a utility for manipulating pc floppies from a sun 
 * through the pcfs filesystem type.
 */

#if !defined(lint) && !defined(SABER) || defined(RCS_HDRS)
static char *rcsid = "$Id: pcfs.c,v 1.6 1993/10/29 16:59:52 ejb Exp $";
#endif /* !lint && !SABER || RCS_HDRS */

#if defined(__svr4__) && defined(sun)
#define SOL2
#endif

#include <stdio.h>
#include <string.h>

#ifdef SOL2
#define MOUNT "mount -F pcfs /dev/diskette /pcfs"
#define RMOUNT "mount -o ro -F pcfs /dev/diskette /pcfs"
#define PATH "PATH=/usr/bin:/usr/sbin"
#else
#define MOUNT "mount /pcfs"
#define RMOUNT "mount -r /pcfs"
#define PATH "PATH=/usr/bin:/usr/etc"
#endif
#define EJECT "eject floppy"

#ifdef __STDC__
void usage(char *whoami)
#else
void usage(whoami)
  char *whoami;
#endif /* __STDC__ */
{
    fprintf(stderr, "Usage: %s mount | rmount | eject\n", 
	    whoami);
    fprintf(stderr, "Use mount to mount a read-write disk, rmount to mount ");
    fprintf(stderr, "read-only, or eject\n");
    fprintf(stderr, "to eject\n");
    exit(1);
}


#ifdef __STDC__
int run_cmd(char *whoami, char *cmd)
#else
int run_cmd(whoami, cmd)
  char *whoami;
  char *cmd;
#endif /* __STDC__ */
{
    int ret;

    ret = system(cmd);

    if ((ret & 0xff) && ((ret & 0xff) != 0177)) {
	fprintf(stderr, "%s: %s was terminated by signal %d", whoami, cmd,
		ret & 0177);
	if (ret & 0200)
	    fprintf(stderr, " and dumped core.\n");
	else
	    fprintf(stderr, ".\n");
    }
    else if ((ret & 0xff) == 0177) {
	fprintf(stderr, "%s: %s was stopped by signal %d\n", whoami, cmd,
		((ret & 0xff00) >> 8));
    }
    else {
	ret = (ret & 0xff00) >> 8;
	if (ret) {
	    fprintf(stderr, "%s: %s exited with a return code %d.\n",
		    whoami, cmd, ret);
	}
    }

    return ret;
}


#ifdef __STDC__
main(int argc, char *argv[])
#else
main(argc, argv)
  int argc;
  char *argv[];
#endif /* __STDC__ */
{
    char *whoami;
    int ret;

    if ((whoami = strrchr(argv[0], '/')) == NULL)
	whoami = argv[0];
    else
	whoami++;

    if (argc != 2) 
	usage(whoami);

    if (putenv(PATH) != 0) {
	fprintf(stderr, "%s: not enough memory to extend path; exiting.\n",
		whoami);
	exit(1);
    }

    if (setuid(0) == -1)
    {
	fprintf(stderr, "%s: setuid(0) failed; continuing anyway...\n",
		whoami);
    }

    if (strcmp(argv[1], "mount") == 0) {
	if (ret = run_cmd(whoami, MOUNT)) {
	    fprintf(stderr, "%s: mount failed; trying read-only.\n", whoami);
	    ret = run_cmd(whoami, RMOUNT);
	}
    }
    else if (strcmp(argv[1], "rmount") == 0) 
	ret = run_cmd(whoami, RMOUNT);
    else if (strcmp(argv[1], "eject") == 0) 
	ret = run_cmd(whoami, EJECT);
    else
	usage(whoami);

    printf("%s: Operation %s.\n", whoami,
	   (ret == 0) ? "was successful" : "failed");

    return ret;
}
