New Script -- run-parts
[pkgusr] / pkgusr / chown
1 #!/bin/bash
2 # Original...
3 # Copyright (c) 2000,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 #  Rewrite, make it a lot more robost and handle most (all?) 
9 #  possibilities of chown'ing. --SY.
10
11 DAISY_CHAIN=""
12
13 for p in $(type -ap chown) ; 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 [ $(id -u) == 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 # An ordinary user cannot change the UID of a file if that UID is
32 # not their own, but chown can also be used to change the GID of a
33 # file as well so it is feasible that an ordinary user could use
34 # chown successfully.
35
36 # preseve the command line as we're gonna mess with it.
37 cmdline="$@"
38 # strip off the options so that $1 becomes the UID:GID arg
39 while [ -n "$1" ]; do
40     case "$1" in
41         (-*) shift ;;
42         (*) break ;;
43     esac
44 done
45
46 # Split USER:GROUP or USER.GROUP into USER and GROUP
47 usrgrp="$1"
48 usr=${usrgrp/[.:]*/}
49 grp=${usrgrp/*[.:]/}
50
51 report=0
52
53 # Catch the case where USER is somebody else.
54 if [ -n "$usr" ]; then
55     printf '%d' "$usr" &>/dev/null
56     if [ $? -eq 0 ]; then
57         if [ $usr -ne $(id -u) ]; then
58             report=1
59         fi
60     else
61         if [ "$usr" != "$(id -un)" ]; then
62             report=1
63         fi
64     fi
65 fi
66
67 # Catch the case where GROUP isn't in our groups.
68 if [ -n "$grp" -a $report -eq 0 ]; then
69     GRP_CHAIN=""
70     printf '%d' "$grp" &>/dev/null
71     if [ $? -eq 0 ]; then
72         GRP_LIST=$(id -G)
73     else
74         GRP_LIST=$(id -Gn)
75     fi
76     for g in ${GRP_LIST}; do
77         if [ "$grp" == "$g" ]; then
78             GRP_CHAIN=$g
79             break
80         fi
81     done
82
83     if [ -z "$GRP_CHAIN" ]; then
84         report=1
85     fi
86 fi
87
88 if [ $report -eq 1 ]; then
89     echo 1>&2 '***' chown ${cmdline}
90 else
91     $DAISY_CHAIN ${cmdline} || exit $?
92 fi
93
94 exit 0
95
96 # Local variables:
97 # sh-basic-offset: 4
98 # End: