#!/bin/sh
#
# This script is used to create and populate a user home directory.
#

# globals
debug=0       # enabled by --debug or --dry-run
dry_run=0     # enabled by --dry-run

# exit codes (constants - don't change these, as they could used in app code)
EXIT_SUCCESS=0
EXIT_INVALID_ARGS=1
EXIT_COMMAND_FAILED=2

# -----------------------------------------------------------------------------
print_usage_and_exit() {
    echo "Usage: $this_script <user-name> <user-id> <group-id>"
    echo
    echo -e "\tThis script will create and populate a user home directory."
    echo
    echo "Options:"
    echo -e "\t--debug    displays debug information while running"
    echo -e "\t--dry-run  shows commands that will be run (but does nothing)"
    echo -e "\t--help     shows this message"
    echo
    exit $EXIT_INVALID_ARGS
}

# -----------------------------------------------------------------------------
command_wrapper() {
    local comment=$1; shift
    local command_line="$*"

    if [ "$debug" -eq "1" ] ; then
        echo "$comment"
        echo "$command_line"
        echo
    fi

    if [ "$dry_run" -eq "1" ] ; then
        return 0
    fi

    if [ "$debug" -eq "1" ] ; then
        $command_line
    else
        $command_line > /dev/null 2> /dev/null
    fi

    return "$?"
}

# -----------------------------------------------------------------------------
exit_on_error() {
    local comment=$1

    command_wrapper "$@"

    if [ "$?" -ne "0" ] ; then
        echo "ERROR: $comment failed"
        exit $EXIT_COMMAND_FAILED
    fi
}

# - MAIN ----------------------------------------------------------------------

this_script=$(basename $0)

# handle options
while :; do
    case "$1" in
        "--help"|"-h"|"-?"|"help") print_usage_and_exit ;;
        "--debug") debug=1 ; shift ;;
        "--dry-run") debug=1 ; dry_run=1; shift ;;
        *) break ;;
    esac
done

if [ "$#" -ne "3" ] ; then
    print_usage_and_exit
fi

username=$1
uid=$2
gid=$3
home_dir="/tmp/users/$username"
ssh_dir="/mnt/sysfs/ssh/users/$username"

command_wrapper "create home dir"    mkdir -p -m 0775 $home_dir
command_wrapper "fix home dir owner" chown $uid:$gid $home_dir
command_wrapper "create ssh dir"     mkdir -p -m 0775 $ssh_dir
command_wrapper "fix ssh dir owner"  chown $uid:$gid $ssh_dir
command_wrapper "link to ssh dir"    ln -nsf $ssh_dir $home_dir/.ssh
command_wrapper "link to config"     ln -nsf /flash0/config  $home_dir/config
command_wrapper "link to archive"    ln -nsf /flash0/archive $home_dir/archive

exit $EXIT_SUCCESS
