#!/bin/ksh
#Tag 1024

#   Setupacct:

findskel()
{

#    Find the account skeleton area. This directory contains the files needed
#    to create and/or update a user account to use the StudioPaint software:
#
#    If there is an apparent skeleton area in ../etc/acct/skel (relative to
#    the pathname of this script), use it for the skeleton area.
#
#    Else if there is an apparent skeleton area in etc/acct/skel (relative to
#    the pathname of this script), use it for the skeleton area.
#
#    Otherwise, we can't find the skeleton area, so we bail out.

    PREF=etc/acct/skel

    pdir=`dirname $0`
    pfc=`echo $pdir | cut -c1`
    if [ "$pfc" = "/" ]; then
        cdir=$pdir
    else
        cdir=$PWD
    fi

    if [ -d $cdir/../$PREF ]; then
        SKELDIR=$cdir/../$PREF
    elif [ -d $cdir/$PREF ]; then
        SKELDIR=$cdir/$PREF
    else
        echo ""
        echo "Cannot find skeleton account directory for account creation and updating."
        echo ""
        echo "Cannot continue -- exiting."
        exit 2
    fi
}

init()
{

#   Set the locale to use English

    LANG=C export LANG
    LC_MESSAGES=C export LC_MESSAGES

#   Define version of this script for echo purposes. If we're on an
#   IBM, tack a ".2" on the end of the version string.

    VERS=V4.0
    if [ X$ibm != X ]; then
        VERS=$VERS.2
    fi

#   Find an acceptable area to place our temp files.

    if [ -d /var/tmp -a -w /var/tmp ]; then
        TMPDIR=/var/tmp
    elif [ -d /usr/tmp -a -w /usr/tmp ]; then
        TMPDIR=/usr/tmp
    else        
        TMPDIR=/tmp
    fi

    OUT=$TMPDIR/out.$$
}

yorn()
{

# Yes or no

    while X=X; do
        read ans
        if [ -z "$ans" ]; then
            ans=foo
        fi
        if [ "$ans" != "yes" -a $ans != "no" ]; then
            echo "Please specify yes or no: \c"
        else
            break 
        fi
    done
    if [ $ans = "yes" ]; then
        return 0
    else
        return 1
    fi
}

quser()
{

#    Query the user and ask them if they wish to update the specified account
#    to use the StudioPaint software. There are a couple cases:
#
#    If we're the superuser and we want to update an account, we need to run
#    as the specified user in a subshell to avoid any permission errors.
#
#    Execute the "su" command without the `-' flag as the flag causes the
#    user's existing dotfiles to be interpreted. This can cause errors.
#
#    The downside of omitting the `-' flag is the current directory is not
#    changed to the home directory of the user whose account is being updated.
#    We assume that the update routine is smart enough to copy the appropriate
#    files to the home directory of the user.

    if [ $ruid -eq 0 ]; then
        env subshell=1 su $usrname -c "$0"
    else

#    If the user account appears to exist, ask the user if it should be updated
#    to use the StudioPaint software. If they say `yes', execute the update
#    routine to update the account to use the software.
#
#    If the update routine exits without the `update' flag being set, it
#    means that the account was not customized to use the StudioPaint software.

        echo ""
        echo "Do you wish to update this account to use the Alias|Wavefront"
        echo "StudioPaint $VERS software? (yes/no): \c"
        if ( yorn ); then
            echo ""
            echo ""
            echo "Updating existing $usrname account to use the Alias|Wavefront"
            echo "StudioPaint $VERS software ..."

            updateacct
            if [ X$update = X ]; then
                echo ""
                echo "The account update failed."
            fi
        fi
    fi
}

cleanup()
{
    rm -f $OUT
    if [ X$subshell = X ]; then
        echo ""
        echo "Press <ENTER> to continue: \c"
        read a
    fi
}

systype()
{

#   Deterime what type of system we're running on. Currently, we only
#   check for AIX (IBM) and IRIX (SGI).

    sys=`uname | cut -c1-4`
    if [ "$sys" = "AIX" ]; then
        ibm=1
    elif [ "$sys" = "IRIX" ]; then
        sgi=1
    else
        echo ""
        echo "Cannot determine system type: `uname -a`"
    fi
}

checknis()
{

#    Based on the machine type, determine if NIS is enabled on this
#    machine.

    if [ X$ibm != X ]; then

#    If we're on an AIX box, check to see if NIS is enabled:
#
#    Determine if NIS/YP (Network Information System) is enabled on this
#    machine. Chop off the first line to get rid of column headers or error
#    messages (which are not split from standard out to standard error).
#
#    The output of:
#
#        lssrc -s ypbind | awk '{print $4}' | sed "1d"
#
#    should be a one line file, indicating the active status of ypbind.

        lssrc -s ypbind | awk '{print $4}' | sed "1d" > $OUT
        if [ ! -z $OUT ]; then
            fgrep -xs active $OUT
            if [ $? -eq 0 ]; then
                ypwhich -m | grep passwd > /dev/null 2>&1
                if [ $? -eq 0 ]; then
                    nison=1
                fi
            fi
        fi
    elif [ X$sgi != X ]; then

#    If we're on an SGI machine, check the `yp' chkconfig flag to see
#    if NIS is enabled. If NIS is enabled, check to see if the password
#    file is mapped by NIS.

        chkconfig yp
        if [ $? -eq 0 ]; then
            ypwhich -m | grep passwd > /dev/null 2>&1
            if [ $? -eq 0 ]; then
                nison=1
            fi
        fi
    fi
}

buildacct()
{

#   Default values for account creation.

    UID=1000
    GID=20
    SHL=/bin/csh

#    The location of the users home directory depends on what type of
#    machine we are creating the account:
#
#    If we are creating the account on an AIX machine, the users home
#    directory will be in /home.
#
#    If we are creating the account on an SGI machine, the users home
#    directory will be in /usr/people.
#
#    If we don't know on what type of machine we're performing the
#    installation, place the users home directory in /usr.

    if [ X$ibm != X ]; then
        HOM=/home/$usrname
    elif [ X$sgi != X ]; then
        HOM=/usr/people/$usrname
    else
        HOM=/usr/$usrname
    fi

#    Find an unused uid for the user account.

    while X=X; do
        if [ X$nison != X ]; then
            (ypcat passwd; cat /etc/passwd) | awk -F: '{print $3}' | grep ${UID} > /dev/null 2>&1
            s=$?
        else
            awk -F: '{print $3}' /etc/passwd | grep ${UID} > /dev/null 2>&1
            s=$?
        fi

        if [ $s -eq 0 ]; then
            echo "INFORMATION, uid $UID in use, let's try another..."
            UID=`expr $UID + 1`
        else
            break
        fi
    done

    echo "INFORMATION, user id '$UID' will be used for user '$usrname'."

    PSF="${usrname}:*:${UID}:${GID}:Alias|Wavefront User:${HOM}:${SHL}"

    echo "INFORMATION, Adding user '$usrname' to /etc/passwd file."
    echo $PSF >> /etc/passwd
    if [ $? != 0 ]; then
        echo ""
        echo "Error adding '$usrname' to /etc/passwd file."
        return
    fi

#    If the users' home directory does not already exist, create it.

    if [ -d $HOM ]; then
        echo "INFORMATION, '$HOM' home directory exists."
    else
        echo "INFORMATION, Creating '$HOM' home directory."
        mkdir -m 755 -p $HOM
    fi

#    Customize the account to use the StudioPaint software.

    echo "INFORMATION, Installing default files:"
    echo ""
    (cd $SKELDIR; tar cf - .) | (cd $HOM; tar xpf -)

#    If we're creating an account on an AIX machine, unpack the CDE
#    environment.

    if [ X$ibm != X -a -f $HOM/.dt ]; then
        (cd $HOM; mv .dt .dt$$; tar xpf .dt$$; rm -f .dt$$)
    fi

#    Fix the permissions of the new account.

    chown -R $UID.$GID $HOM
    chmod -R u+rw $HOM

    echo ""
    echo "INFORMATION, Account successfully created"
    echo ""
    echo "New Account Summary:"
    echo ""
    echo "    User:     $usrname"
    echo "    Password: <disabled>"
    echo "    User ID:  $UID"
    echo "    Group ID: $GID"
    echo "    Home:     $HOM"
    echo "    Shell:    $SHL"
}

updateacct()
{

#    Before we update the account, make sure the users' home directory
#    exists. If it doesn't exit, we can't do anything, so we exit.

    if [ ! -d ~$usrname ]; then
        echo ""
        echo "The $usrname account does not appear to have a home directory."
        echo ""
        echo "It cannot be customized to use the Alias|Wavefront StudioPaint $VERS software."
        return
    fi
    uhome=`echo ~$usrname`

    tmp=.env_`date +%b%d`
    a=1
    save_dir=$tmp

    while [ -e $uhome/$save_dir ]; do
        save_dir=$tmp.$a
        a=`expr $a + 1`
    done

#   If any of the users' existing dotfiles are different than the StudioPaint
#   versions, they will be saved in a subdirectory of the users' home
#   directory. We call this the "save directory".
#
#   Create the save directory in preparation of moving files into it.

    mkdir $uhome/$save_dir > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo ""
        echo "Failed to make backup directory $uhome/$save_dir."
        echo ""
        echo "Cannot update the $usrname account."
        echo ""
        return
    fi
    rmsvdir=1

    cd $SKELDIR

#   Install the StudioPaint dotfiles in the users' home directory, moving
#   existing versions to the save directory if they differ from the
#   StudioPaint versions.
#
#   Be sure to make the files writable by the user. The permissions
#   of files coming off the CD can be strange.

    echo ""
    echo "Copying Alias|Wavefront StudioPaint $VERS dot files ..."
    echo ""
    for f in  `ls -a`; do
        if [ $f = "." -o $f = ".." ]; then
            continue
        fi

        if [ -e $uhome/$f ];  then
            cmp -s $f $uhome/$f
            if [ $? -eq 0 ]; then
                continue
            fi

            echo "Saving original copy of $uhome/$f as $uhome/$save_dir/$f"
            mv $uhome/$f $uhome/$save_dir/$f
            rmsvdir=0
        fi

#    Use tar to copy the files (and directories) individually. I originally
#    used the "cp" command, but it was causing problems on the IBM.

        tar cf - $f | (cd $uhome; tar xpf -)
        if [ -d $f ]; then
            chmod -R u+rw $uhome/$f
        else
            chmod u+rw $uhome/$f

#   If we're on an IBM, unpack the CDE environment.

            if [ X$ibm != X -a $f = .dt ]; then
                (cd $uhome; mv .dt .dt$$; tar xpf .dt$$; rm -f .dt$$)
            fi
        fi
    done

#    If no files were moved to the save directory, remove it.

    if [ $rmsvdir -eq 1 ]; then
        rmdir $uhome/$save_dir
    fi
    update=1
}

checkuname()
{

#    If the superuser wants to setup a demo account, ask them the preferred
#    username and check for it's existence. Verify that the specified username
#    is not more than 8 characters long.

    echo ""
    while X=X; do
        echo "What is the username of the account? (i.e.: awdemo): \c"
        read usrname
        if [ -z "$usrname" ]; then
            continue
        fi
        set $usrname
        if [ $# -eq 1 ]; then
            first8=`echo $usrname | cut -c1-8`
            if [ $first8 != $usrname ]; then
                echo ""
                echo "The username $usrname is too long."
                echo ""
                echo "It must be a maximum of 8 characters.  Please try again."
                echo ""
            else
                break
            fi
        fi  
    done

#    Test for existence of the demo account by searching the password file(s)
#    for a password entry for the specified user. If NIS is enabled, search
#    both the NIS password file and the local password file for an entry,
#    otherwise only search the local password file for an entry.
#
#    If the specified account appears to already exist (it has a password
#    entry), conditionally perform an update.
#
#    If we can't find a password entry for the specified user, conditionally
#    create the account.
#
#    Check for a local password entry before and after to determine if an entry
#    is added. If a password entry is added to the local password file, execute
#    the passwd command to set its' password.

    echo ""
    echo "Checking for existence of the $usrname account ... \c"

    if [ X$nison != X ]; then
        (ypcat passwd; cat /etc/passwd) | grep "^${usrname}:" > /dev/null 2>&1
        s=$?
    else
        grep "^${usrname}:" /etc/passwd > /dev/null 2>&1
        s=$?
    fi

    if [ $s -eq 0 ]; then
        echo "it exists."
        quser
    else
        nopwentery=1
        echo "it does not"
        echo "appear to exist."
        echo ""
        echo "Do you wish to create the account and customize it to use the"
        echo "Alias|Wavefront StudioPaint $VERS software? (yes/no): \c"
        if ( yorn ); then
            echo ""
            echo "Creating $usrname account ..."
            echo ""
            buildacct $usrname
            grep -s "^${usrname}:" /etc/passwd > /dev/null 2>&1
            if [ $? -eq 0 -a X$nopwentery != X ]; then
                echo ""
                echo "A password entry for the $usrname account has been added to the local"
                echo "password file."
                echo ""
                echo "Please specify a password for the $usrname account."
                passwd $usrname
                echo ""
                echo "If your site uses NIS to administer user accounts, you may wish to add the"
                echo "password entry for the $usrname account to the NIS master password file and"
                echo "remove it from the local password file."
                echo ""
                create=1
            fi
        fi
    fi
}

# Main

#   Perform some initialization:
#
#   - setup signal handling
#   - Determine the location of the account skeleton area
#   - define the location of a temporary file
#   - Determine the system type

trap "cleanup; exit 2" 1 2 3 15

findskel
systype
init

#    Get the userid of the current user. If the current user is the
#    superuser (userid is zero), call the `checkuname' routine to
#    determine if a user account is to be created or updated.
#
#    If the current user is not the superuser, the user has the choice
#    of updating their account to use the StudioPaint software.

ruid=`id | sed "s/uid=\([0-9]*\)(.*/\1/"`
if [ $ruid -eq 0 ]; then
    checknis
    checkuname
else
    usrname=`id | sed "s/.*(\(.*\)) .*/\1/"`
    quser
fi

if [ -n "$create" -o -n "$update" ]; then
    echo ""
    echo "The $usrname account has been \c"
    if [ -n "$create" ];  then
        echo "created\c"
    elif [ -n "$update" ]; then
        echo "updated\c"
    fi
    echo " to use the Alias|Wavefront StudioPaint"
    echo "$VERS software."
fi

cleanup
exit 0
