#!/bin/sh -e

##########################################################################
#   Script description:
#       
#   Arguments:
#       
#   Returns:
#       
#   History:
#   Date        Name        Modification
#   2014-03-26  root        Begin
##########################################################################

usage()
{
    printf "Usage: $0 username password-file shadow-file group-file\n"
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ $# != 4 ]; then
    usage
fi

user_name=$1
old_pw_file=$2
old_shadow_file=$3
old_group_file=$4

# Get user info from $old_pw_file
# uid, gid, comment, home, shell
user_id=`awk -F : -v user_name=$user_name '$1 == user_name { print $3 }' $old_pw_file`
group_id=`awk -F : -v user_name=$user_name '$1 == user_name { print $4 }' $old_pw_file`
gecos=`awk -F : -v user_name=$user_name '$1 == user_name { print $5 }' $old_pw_file`
home=`awk -F : -v user_name=$user_name '$1 == user_name { print $6 }' $old_pw_file`
shell=`awk -F : -v user_name=$user_name '$1 == user_name { print $7 }' $old_pw_file`

# Create group first if necessary
group_name=`awk -F : -v group_id=$group_id '$3 == group_id { print $1 }' $old_group_file`

# printf "$user_name $group_name $user_id $group_id '$gecos' $home $shell\n"

case `auto-ostype` in
RHEL)
    # -f = return success even if the group already exists
    groupadd -f -g $group_id $group_name

    # Create user
    groups="`groups $user_name | awk -F ': ' '{print $2}' | cut -s -d ' ' -f 2- | tr ' ' ','`"
    if [ -z "$groups" ]; then
	useradd -c "\"$gecos\"" -d $home -g $group_id -M \
	    -s $shell -u $user_id $user_name
    else
	# Sync supplementary groups first
	useradd -c "\"$gecos\"" -d $home -g $group_id -M \
	    -s $shell -u $user_id -G "$groups" $user_name
    fi
    ;;

FreeBSD)
    if ! pw groupadd $group_name -g $group_id; then
	printf 'Group add failed.\n'
    fi

    # Create user
    groups="`groups $user_name | cut -s -d ' ' -f 2- | tr ' ' ','`"
    if [ -z "$groups" ]; then
	pw useradd $user_name -c "\"$gecos\"" -d $home -m -g \
	    $group_id -s $shell -u $user_id
    else
	# Sync supplementary groups first
	pw useradd $user_name -c "\"$gecos\"" -d $home -m -g \
	    $group_id -s $shell -u $user_id -G "$groups"
    fi
    ;;

*)
    auto-unsupported-os $0
    exit 1
    ;;

esac

# Restore password
pw="`awk -F : '$1 == "'$user_name'" { print $0 }' $old_shadow_file`"
auto-restore-pw $user_name "$pw"

