/* chmod (change file mode) for GNU,
   Copyright (C) 1985 Richard M. Stallman

		       NO WARRANTY

  BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.

 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.

		GENERAL PUBLIC LICENSE TO COPY

  1. You may copy and distribute verbatim copies of this source file
as you receive it, in any medium, provided that you conspicuously
and appropriately publish on each copy a valid copyright notice
"Copyright (C) 1986 Richard M. Stallman"; and include following the
copyright notice a verbatim copy of the above disclaimer of warranty
and of this License.

  2. You may modify your copy or copies of this source file or
any portion of it, and copy and distribute such modifications under
the terms of Paragraph 1 above, provided that you also do the following:

    a) cause the modified files to carry prominent notices stating
    that you changed the files and the date of any change; and

    b) cause the whole of any work that you distribute or publish,
    that in whole or in part contains or is a derivative of this
    program or any part thereof, to be freely distributed
    and licensed to all third parties on terms identical to those
    contained in this License Agreement (except that you may choose
    to grant more extensive warranty protection to third parties,
    at your option).

  3. You may copy and distribute this program or any portion of it in
compiled, executable or object code form under the terms of Paragraphs
1 and 2 above provided that you do the following:

    a) cause each such copy to be accompanied by the
    corresponding machine-readable source code, which must
    be distributed under the terms of Paragraphs 1 and 2 above; or,

    b) cause each such copy to be accompanied by a
    written offer, with no time limit, to give any third party
    free (except for a nominal shipping charge) a machine readable
    copy of the corresponding source code, to be distributed
    under the terms of Paragraphs 1 and 2 above; or,

    c) in the case of a recipient of this program in compiled, executable
    or object code form (without the corresponding source code) you
    shall cause copies you distribute to be accompanied by a copy
    of the written offer of source code which you received along
    with the copy you received.

  4. You may not copy, sublicense, distribute or transfer this program
except as expressly provided under this License Agreement.  Any attempt
otherwise to copy, sublicense, distribute or transfer this program is void and
your rights to use the program under this License agreement shall be
automatically terminated.  However, parties who have received computer
software programs from you with this License Agreement will not have
their licenses terminated so long as such parties remain in full compliance.

 In other words, you are welcome to use, share and improve this program.
 You are forbidden to forbid anyone else to use, share and improve
 what you give them.   Help stamp out software-hoarding!  */

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <ctype.h>

#define USAGE "Usage: chmod [ugoa][+-=][rwxstugo] file ..."
short int whomask = 01000;

main(argc, argv)
int argc;
char **argv;
{
  int bad = 0, i;

  if (argc < 2)
    fatal(USAGE);

  for (i = 2; i < argc; i++)
    if (change(argv[i], argv[1]) < 0)
      bad++;

  exit (bad);
}

int
change(file, modestr)
char *file, *modestr;
{
  struct stat sbuf;
  int mode = 0, i;
  char op;

  if (stat(file, &sbuf) < 0) {
    fprintf(stderr, "chmod: can't access %s\n", file);
    return -1;
  }

  for (i = 0; modestr[i] != '\0'; i++)
    if (!(isdigit(modestr[i]) && modestr[i] <= '7'))
      goto notnumeric;

  for (i = 0; modestr[i] != 0; i++)
    mode = (mode << 3) | (modestr[i] - '0');
  goto gotmode;

 notnumeric:

  mode = sbuf.st_mode;

  for ( ; *modestr != '\0'; modestr++) {
    switch (*modestr) {
    case 'u':
      whomask |= 04700;
      break;
    case 'g':
      whomask |= 02070;
      break;
    case 'o':
      whomask |= 07;
      break;
    case '+':
    case '-':
    case '=':
      /* if anything has happened, take the operator;
       * otherwise, back up the cursor so the op gets taken
       * care of next time, then fall through to case 'a'.
       * note umask is guaranteed to be 9 bits, so this can't loop.
       */
      if (whomask != 01000)
	goto newop;
      modestr--;
    case 'a':
      whomask = 07777 & ~umask(0);
      break;
    default:
      fatal("chmod: invalid mode\n");
    }
  }
  fatal("chmod: invalid mode\n"); /* never found an operator */

 newop:
  for ( ; *modestr != '\0'; modestr++) {
    switch (*modestr) {
    case '+':
    case '-':
    case '=':
      op = *modestr;
      break;
    case 'r':
      mode = apply(mode, op, 0444);
      break;
    case 'w':
      mode = apply(mode, op, 0222);
      break;
    case 'x':
      mode = apply(mode, op, 0111);
      break;
    case 's':
      mode = apply(mode, op, S_ISUID | S_ISGID);
      break;
    case 't':
      mode = apply(mode, op, S_ISVTX);
      break;
    case 'u':
      i = sbuf.st_mode & 0700;
      mode = apply(mode, op, i | i >> 3 | i >> 6);
      break;
    case 'g':
      i = sbuf.st_mode & 070;
      mode = apply(mode, op, i << 3 | i | i >> 3);
      break;
    case 'o':
      i = sbuf.st_mode & 07;
      mode = apply(mode, op, i << 6 | i << 3 | i);
      break;
    default:
      fatal("chmod: invalid mode\n");
      /* NOTREACHED */
    }
  }

 gotmode:
  
  if (chmod(file, mode) < 0) {
    fprintf(stderr, "chmod: can't change %s\n", file);
    return -1;
  }
  return 0;
}

fatal(str)
char *str;
{
  fprintf(stderr, str);
  exit (1);
}

apply(mode, op, f)
int mode, f;
char op;
{
  f &= whomask;

  switch (op) {
  case '=':
    mode &= ~whomask;		/* fall through */
  case '+':
    return mode | f;
  case '-':
    return mode & ~f;
  default:
    fatal("chmod: internal error: apply.  pls report bug.\n");
  }
}
