|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +# set -x |
| 4 | + |
| 5 | +TARGET_USER=$1 |
| 6 | +TARGET_GROUP=$2 |
| 7 | +TARGET_DIR=$3 |
| 8 | + |
| 9 | +function get_target_uid() { |
| 10 | + echo $(stat -c '%u' $TARGET_DIR) |
| 11 | +} |
| 12 | + |
| 13 | +function get_target_gid() { |
| 14 | + echo $(stat -c '%g' $TARGET_DIR) |
| 15 | +} |
| 16 | + |
| 17 | +function get_current_uid_of() { |
| 18 | + echo $(getent passwd $1 | cut -d: -f3) |
| 19 | +} |
| 20 | + |
| 21 | +function get_current_username_of() { |
| 22 | + echo $(getent passwd $1 | cut -d: -f1) |
| 23 | +} |
| 24 | + |
| 25 | +function get_current_gid_of() { |
| 26 | + echo $(getent group $1 | cut -d: -f3) |
| 27 | +} |
| 28 | + |
| 29 | +function get_current_groupname_of() { |
| 30 | + echo $(getent group $1 | cut -d: -f1) |
| 31 | +} |
| 32 | + |
| 33 | +# Exist if UID and GID already match |
| 34 | +if [[ get_target_uid -eq $(get_current_uid_of "$TARGET_USER") && get_target_gid -eq $(get_current_gid_of "$TARGET_GROUP") ]]; then |
| 35 | + # Nothing to do here... |
| 36 | + exit 0 |
| 37 | +fi |
| 38 | + |
| 39 | +# Remove conflicting group if needed |
| 40 | +if [[ $(get_target_gid) -ne $(get_current_gid_of "$TARGET_GROUP") && -z $(get_current_gid_of "$TARGET_GROUP") && $(get_target_gid) -ne 0 ]]; then |
| 41 | + groupdel $(get_target_gid) |
| 42 | + if [[ $? -ne 0 ]]; then |
| 43 | + exit $? |
| 44 | + fi |
| 45 | +fi |
| 46 | + |
| 47 | +# Remove conflicting user if needed |
| 48 | +if [[ $(get_target_uid) -ne $(get_current_uid_of "$TARGET_USER") && -z $(get_current_uid_of "$TARGET_USER") && $(get_target_uid) -ne 0 ]]; then |
| 49 | + userdel $(get_target_uid) |
| 50 | + if [[ $? -ne 0 ]]; then |
| 51 | + exit $? |
| 52 | + fi |
| 53 | +fi |
| 54 | + |
| 55 | +# Create target group if needed |
| 56 | +if [[ $TARGET_GROUP != $(get_current_groupname_of "$TARGET_GROUP") ]]; then |
| 57 | + groupadd -g $(get_target_gid) $TARGET_GROUP |
| 58 | +fi |
| 59 | + |
| 60 | +# Create target user if needed |
| 61 | +if [[ $TARGET_USER != $(get_current_username_of "$TARGET_USER") ]]; then |
| 62 | + useradd -u $(get_target_uid) $TARGET_USER |
| 63 | +fi |
| 64 | + |
| 65 | +# Modify the GID if needed |
| 66 | +if [[ $(get_target_gid) -ne $(get_current_gid_of "$TARGET_GROUP") ]]; then |
| 67 | + groupmod -g $(get_target_gid) $TARGET_GROUP |
| 68 | + if [[ $? -ne 0 ]]; then |
| 69 | + exit $? |
| 70 | + fi |
| 71 | +fi |
| 72 | + |
| 73 | +# Modify the UID if needed |
| 74 | +if [[ $(get_target_uid) -ne $(get_current_uid_of "$TARGET_USER") ]]; then |
| 75 | + usermod -u $(get_target_uid) $TARGET_USER |
| 76 | + if [[ $? -ne 0 ]]; then |
| 77 | + exit $? |
| 78 | + fi |
| 79 | +fi |
0 commit comments