/*
 * move -- a program designed to move ./vmunix to /vmunix while saving
 *  old vmunixes in /vmunix.0 through /vmunix.N for N a parameter.
 */

#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#include <sys/file.h>

#define N_VERSIONS_SAVED 1

#define CHECK(call) if((call)<0){perror(0);exit(1);}

char host[256];

char buf[4096];

int copy(from,to)
char *from;
char *to;
{
 register int ffd;
 register int tfd;
 register int l;

 ffd = open(from,O_RDONLY,0);
 if (ffd < 0)
  { return(-1);
  }
 tfd = open(to,O_WRONLY|O_CREAT|O_TRUNC,0755);
 if (tfd < 0)
  { close(ffd);
    return(-1);
  }
 while ((l=read(ffd,buf,sizeof(buf))) > 0)
  { write(tfd,buf,l);
  }
 close(ffd);
 close(tfd);
 return(l);
}

main()
{
 char name1[256];
 char name2[256];
 int i;
 int j;
 char *cp;

 if (getwd(host) == 0)
  { fprintf(stderr,"getwd: %s\n",host);
    exit(1);
  }
 cp = rindex(host,'/');
 if (cp)
  { char *dp;
    cp ++;
    dp = host;
    while (*dp++ = *cp++) ;
  }
 for (cp=host;*cp;cp++)
  { if (isascii(*cp) && isupper(*cp))
     { *cp = tolower(*cp);
     }
  }
 umask(0);
 if (access("vmunix",X_OK) < 0)
  { fprintf(stderr,"vmunix isn't executable!\n");
    exit(1);
  }
 for (i=0;i<N_VERSIONS_SAVED-1;i++)
  { sprintf(name1,"/vmunix.%d",i);
    if (access(name1,F_OK) < 0)
     { break;
     }
  }
 for (j=i-1;j>=0;j--)
  { sprintf(name1,"/vmunix.%d",j);
    sprintf(name2,"/vmunix.%d",j+1);
    fprintf(stderr,"mv %s %s\n",name1,name2);
    CHECK(rename(name1,name2));
  }
 sprintf(name2,"/vmunix.N",host);
 printf("cp vmunix %s\n",name2);
 CHECK(copy("vmunix",name2));
 sprintf(name1,"/vmunix",host);
 sprintf(name2,"/vmunix.0",host);
 printf("mv %s %s\n",name1,name2);
 CHECK(rename(name1,name2));
 sprintf(name2,"/vmunix.N",host);
 printf("mv %s %s\n",name2,name1);
 CHECK(rename(name2,name1));
 exit(0);
}
