#!/bin/bash

# Creates gterm user, if not present, and starts host connection
#  Note: gterm users are locked and cannot login directly
# If user is --all, host connection is started for all existing users (excluding ADMIN)
# To reset user terminals, use "gterm_user_setup --all restart"

HOME_MNT=/home
ADMIN=ubuntu
GRAPHTERM_DIR=.graphterm
GRAPHTERM_AUTH=_gterm_auth.txt

if [ $# -lt 1 ]; then
    echo "Usage: gterm_user_setup (username|--all) [activate/stop/restart [server_name [gtermhost arguments]]]"
    exit 1
fi

username=$1
action=activate
server=localhost
rem_args=""

if [ $# -gt 1 ]; then
    action=$2
fi

if [ $# -gt 2 ]; then
    server=$3
fi

if [ $# -gt 3 ]; then
    shift 3
    rem_args="$@"
fi

if [ ! -d $HOME_MNT ]; then
    echo "Home directory $HOME_MNT does not exist"
    exit 1
fi


if [ "$username" = "--all" ]; then
    host_list=""
    cd  $HOME_MNT
    for host in *; do
        if [ "$host" != "$ADMIN" ]; then
	    host_list="$host_list $host"
	fi
    done

elif [[ "$username" =~ ^[a-z][a-z0-9-]*$ ]]; then
    host_list=$username
    if getent passwd $username > /dev/null 2>&1; then
	echo "User $username already present"
    else
	homedir=$HOME_MNT/$username
	if [ -e $homedir ]; then
	    echo "Home directory already exists"
	else
            # Create new user
	    echo "Creating new user and group $username"
	    useradd --user-group --create-home --home $homedir --shell /bin/bash $username
	    sudo -u $username chmod 0711 $homedir

	    sudo -u $username mkdir $homedir/$GRAPHTERM_DIR
	    sudo -u $username chmod 0700 $homedir/$GRAPHTERM_DIR
    
            # Lock user password (i.e., no direct logins allowed)
	    passwd -l $username

	fi
    fi
else
    echo "Invalid username $username"
    exit 1
fi

for host in $host_list; do
    # Update authentication code for host/user
    if [ "$host" != "$ADMIN" ] && [ -d $HOME_MNT/$host/$GRAPHTERM_DIR ]; then
	/usr/local/bin/gauth -w --admin=$ADMIN --server=$server $host
        if [ "$server" = "localhost" ]; then
	    auth_file=$HOME_MNT/$host/$GRAPHTERM_DIR/${host}$GRAPHTERM_AUTH
	else
	    auth_file=$HOME_MNT/$host/$GRAPHTERM_DIR/${host}@$server$GRAPHTERM_AUTH
        fi
	chown ${host}:$host $auth_file

        # Start client for host
        uid=`id -u $host`
	sudo -u $host -H gtermhost --daemon=$action --auth_file=$auth_file $rem_args $host
    fi
done
