#!/bin/sh -e

##########################################################################
#   Script description:
#       Restore a user with original uid, gid, etc.
#       
#   History:
#   Date        Name        Modification
#   2015-01-31  J Bacon     Begin
##########################################################################

usage()
{
    printf "Usage: $0 username old-passwd-file old-shadow-file old-group-file old-pw-age-dir\n"
    exit 1
}


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

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

auto-root-check $0

if ! cluster-check-cron-updates; then
    exit 0
fi

user_name=$1
old_passwd_file=$2
old_shadow_file=$3
old_group_file=$4
old_pw_age_dir=$5
old_pw_age=`awk '{ print $1 }' $old_pw_age_dir/$user_name`

os_type=`auto-ostype`

case $os_type in
FreeBSD)
    shadow_pw='/etc/master.passwd'
    ;;

RHEL)
    shadow_pw='/etc/shadow'
    ;;

*)
    printf "$0: Not supported on $(auto-ostype).\n"
    exit 1
    ;;

esac

# Create account if it doesn't exist
found_user=`awk -F : '$1 == "'$user_name'" { print $1 }' /etc/passwd`
if [ 0$found_user != 0$user_name ]; then
    # cluster-useradd specify all attributes
    # Get attributes from passwd.old rather than users.txt, since
    # chsh/chfn may have been used
    user_id=`awk -F : '$1 == "'$user_name'" { print $3 }' $old_passwd_file`
    group_id=`awk -F : '$1 == "'$user_name'" { print $4 }' $old_passwd_file`
    gecos="`awk -F : '$1 == "'$user_name'" { print $5 }' $old_passwd_file`"
    shell=`awk -F : '$1 == "'$user_name'" { print $7 }' $old_passwd_file`
    
    group_name=`awk -F : -v group_id=$group_id '$3 == group_id { print $1 }' $old_group_file`
    found_group_name=`awk -F : -v group_id=$group_id '$3 == group_id { print $1 }' /etc/group`
    
    # cluster-useradd will create a group with GID=UID if the group
    # doesn't exist, so create it with the original GID beforehand.
    if [ 0$found_group_name = 0 ]; then
	printf "$0: Creating $group_name $group_id\n"
	case $os_type in
	FreeBSD)
	    pw groupadd $group_name -g $group_id
	    ;;
	RHEL)
	    groupadd -g $group_id $group_name
	    ;;
	esac
    fi
    
    NOPW=true
    export NOPW
    if ! cluster-useradd $user_name $user_id $group_name "$gecos" $shell $old_pw_age; then
	printf "$cmd failed.\n"
    fi
else
    printf "User $user_name already exists.\n"
    exit 1
fi

printf "Restore local password? (Not needed if using LDAP/AD) [y]/n "
read restore_pw
if [ 0$restore_pw != 0n ]; then
    cluster-transfer-pw $user_name $old_shadow_file $old_pw_age_dir
else
    cluster-lock-local-pw $user_name
fi
