#!/bin/sh


#################################################################
# File:         re-login                                        #
# Author:       Przemysław "Winnetou" Wilkosz                   #
# Contact:      wilkosz.p@gmail.com                             #
# jid:          winnetou@jabster.pl                             #
# Author:       Mateusz 'thalcave' Chynowski                    #
# Contact:      thalcave@gmail.com                              #
# jid:          thalcave@jid.dug.net.pl                         #
#                                                               #
# Desc:         Scrip allows to change user login               #
# Copyleft:     All right reversed. Take, use and share         #
# Licence:      GNU GPL                                         #
# Thanks to:    lis6502  <lis6520@gmail.com>                    #
#################################################################

OLDNICK=$1
NEWNICK=$2


help()
{
        echo "script allows to change loginname of selected user"
        echo "$0 old-username new-username"

}

update_files()
{

        if [ "$1" = "group" ]
        then

                sed -i -e "s/\(^\|:\|,\)$OLDNICK\(,\|:\|$\)/\1$NEWNICK\2/g" /etc/$1

        else

          sed -i -e "s/\(^\|\/\)$OLDNICK:/\1$NEWNICK:/g" /etc/$1

        fi

}


if [ $# -ne 2 ]
then

        help

elif [ $# -eq 2 ]
then

        if  [ "$NEWNICK" = "$OLDNICK" ]
        then
                echo "new-login = old-login. Abording"
                exit 666;
        else
                if [ -n $(grep "^$NEWNICK:" /etc/passwd) ]
                then

                        echo "$NEWNICK already exist abording"
                        exit 666;

                fi

        fi

        DOM=$(grep ^${OLDNICK}: /etc/passwd |cut -d: -f 6 |sed "s/\/${OLDNICK}//")
        mv $DOM/$OLDNICK $DOM/$NEWNICK
        update_files group
        update_files passwd
        update_files shadow

else

   help

fi
