leancode
8/15/2018 - 10:01 AM

composer start-up script to NOT run composer as root user accidentally.

composer start-up script to NOT run composer as root user accidentally.

#! /bin/bash
# composer start-up script to NOT run composer as root user accidentally.
# Lets say you are in /home/john/ as root and accidently run composer update
# normally composer would just warn you that you are root and continue anyway, possibly wrecking permissions or worse.
# This script looks at owner of the current directoy and check if the user actually exists.
# If that is affirmative it would then run composer as that owner from the current location.
#
# Instructions:
# put the actual composer.phar into /usr/local/bin so its in the path and available
# put this in the same location and just call it composer

# first section checks if its run as a none root user and if so just executes composer as usual
if [ $USER != "root" ]; then
composer.phar "$@"
exit
fi

# from here on we are root

# attempting to get the user, this can sometimes fail of course but we can try ;-)
if [[ "$@" == *"self-update"* || "$@" == *"selfupdate"* ]]; then
    composer.phar "$@"
    exit
fi

COMPOSER_USER=`stat -c '%U' ./`

# check if something was found
if [[ -z "$COMPOSER_USER" ]]; then
    echo Unable to get user of current directory.
    exit 1
fi

# check that the something found is a valid user
ret=true
getent passwd $COMPOSER_USER >/dev/null 2>&1 && ret=false
if $ret ; then
    echo Unable to get user of current directory.
    echo Found \"$COMPOSER_USER\" but user does not exist.
    exit 1
fi

# all good call composer as the user found
if [ ! -f composer.phar ]; then
    echo Executing:"sudo -u $WP_USER /usr/local/bin/composer.phar \"$@\""
    sudo -u $COMPOSER_USER /usr/local/bin/composer.phar "$@"
else
    echo Executing:"sudo -u $WP_USER -i -- /usr/local/bin/composer.phar \"$@\""
    sudo -u $COMPOSER_USER -i -- /usr/local/bin/composer.phar "$@"
fi
exit