/* $Copyright:	$
 * Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990 
 * Sequent Computer Systems, Inc.   All rights reserved.
 *  
 * This software is furnished under a license and may be used
 * only in accordance with the terms of that license and with the
 * inclusion of the above copyright notice.   This software may not
 * be provided or otherwise made available to, or used by, any
 * other person.  No title to or ownership of the software is
 * hereby transferred.
 */

#ident	"$Header: mvdir.c 1.8 89/06/07 $@(#)mvdir:mvdir.c	1.4"

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>

main(argc,argv)
int	argc;
char	*argv[];
{
	struct stat stbuf;
	char	dest[MAXPATHLEN];

	if (argc != 3) {
		fprintf(stderr, "Usage: mvdir fromdir newname\n");
		exit(2);
	}

	if (strcmp(argv[1], ".") == 0) {
		fprintf(stderr, "mvdir: cannot move '.'\n");
		exit(2);
	}

	strcpy(dest, argv[2]);
	if (stat(dest, &stbuf) != -1) {
		if((stbuf.st_mode & S_IFMT) == S_IFDIR) {

			char *ptr;

			/*
			 * Make sure argv[2]/basename(argv[1]) does not exist.
			 */
			
			strcat(dest,"/");

			if (ptr = strrchr(argv[1], '/')) {
				strcat(dest, ++ptr);
			} else {
				strcat(dest, argv[1]);
			}

			/*
			 * If the stat doesn't fail it means the file is already
			 * there.  This is an error.
			 */

			errno = 0;
			if (stat(dest, &stbuf) != -1) {
				fprintf(stderr, "%s exists\n", dest);
				exit(1);
			}
		} else {
			fprintf(stderr, "%s must be a directory or must not exist\n", argv[2]);
			exit(1);
		}
	}

	/*
	 * Make sure arg1 is a directory.
	 */

	if(stat(argv[1], &stbuf) == -1) {
		perror(argv[1]);
		exit(1);
	}

	if((stbuf.st_mode & S_IFMT) != S_IFDIR) {
		fprintf(stderr, "%s must be a directory\n", argv[1]);
		exit(1);
	}

	if(rename(argv[1], dest) == -1) {
		if(errno == EINVAL) {
			fprintf(stderr, "arguments have common path\n");
			exit(1);
		}
		perror("mvdir");
		exit(1);
	}

	exit(0);
}
