Major overhaul -- most scripts rewritten or updated.
[pkgusr] / usr / lib / 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 [ $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 # 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" && ("$usr" != "$(id -un)" ||
55                 ($usr -ge 0 && $usr -ne $(id -u))) ]]; then
56     report=1
57 fi
58
59 # Catch the case where GROUP isn't in our groups.
60 if [ -n "$grp" -a $report -eq 0 ]; then
61     GRP_CHAIN=""
62     if [ $grp -ge 0 2>/dev/null ]; then
63         GRP_LIST=$(id -G)
64     else
65         GRP_LIST=$(id -Gn)
66     fi
67     for g in ${GRP_LIST}; do
68         if [ "$grp" == "$g" ]; then
69             GRP_CHAIN=$g
70             break
71         fi
72     done
73
74     if [ -z "$GRP_CHAIN" ]; then
75         report=1
76     fi
77 fi
78
79 if [ $report -eq 1 ]; then
80     echo 1>&2 '***' chown "$cmdline"  
81 else
82     exec $DAISY_CHAIN "$cmdline" || exit $?
83 fi
84
85 exit 0
86
87 # Local variables:
88 # sh-basic-offset: 4
89 # End: