555ca3f1bd6fc820eba4a1813cfdd3dc381df2cf
[pkgusr] / usr / lib / pkgusr / chmod
1 #!/bin/bash
2 # Original...
3 # Copyright (c) 2004 Matthias S. Benkmann <article AT winterdrache DOT de>
4 # You may do everything with this code except misrepresent its origin.
5 # PROVIDED `AS IS' WITH ABSOLUTELY NO WARRANTY OF ANY KIND!
6
7 # Copyright (C) 2014 Steve Youngs <steve@steveyoungs.com>
8 #  Handle all possible file modes as well as chmod options and symbolic
9 #  modes.
10
11 DAISY_CHAIN=""
12
13 for p in $(type -ap chmod) ; do
14     if [ ! $p -ef $0 ]; then
15         DAISY_CHAIN=$p
16         break
17     fi
18 done
19
20 if [ ! -n "$DAISY_CHAIN" ]; then
21     echo 1>&2 '***' Cannot find real ${0##*/} command 
22     exit 1
23 fi
24
25 if [ $UID == 0 ]; then
26     echo 1>&2 '***' $(dirname $0) should not be in root\'s \$PATH
27     echo 1>&2 '***' call "$DAISY_CHAIN $@" directly.
28     exit 1
29 fi
30
31 # Save the original cmdline as we're gonna mess with it
32 cmdline="$@"
33
34 reportmsg="*** chmod $cmdline"
35 report=0
36
37 # Remove any options so $1 becomes the perm arg, however save the
38 # options for later
39 opts=""
40 while [ -n "$1" ]; do
41     case $1 in
42         (-*) opts="$opts $1" ; shift ;;
43         (*) break ;;
44     esac
45 done
46 # $1 should now be the perm arg
47
48 # Octal or symbolic?
49 if [ $1 -ge 0 2>/dev/null ]; then
50     perm=$1
51 else
52     touch /tmp/hack-o-matic-4500
53     chmod $1 /tmp/hack-o-matic-4500
54     perm=$(stat --printf "%a" /tmp/hack-o-matic-4500)
55     rm -f /tmp/hack-o-matic-4500
56 fi
57
58 # if it is 4 digits, they're trying to do funky shit
59 if [ $perm -gt 999 ]; then
60     # Chop off the 1st digit (the set{uid,gid,sticky} bit)
61     perm=${perm/?/}
62     echo 1>&2 "$reportmsg"
63 fi
64
65 # kill off $1 and replace it with our maybe sanitised $perm
66 shift 1; set -- $perm "$@"
67
68 exec $DAISY_CHAIN "$opts $@" || exit $?
69 exit 0
70
71 # Local variables:
72 # sh-basic-offset: 4
73 # End: