#!/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

HOME_MNT=/home
ADMIN=ubuntu
GRAPHTERM_DIR=.graphterm
GRAPHTERM_AUTH=graphterm_auth

server=localhost

if [ $# -lt 1 ]; then
    echo "Usage: gterm_user_setup (username|--all) [server_name]"
    exit 1
fi

username=$1

if [ $# -gt 1 ]; then
    server=$2
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
    if getent passwd $username > /dev/null 2>&1; then
	echo "User $username already present"
	exit 1
    fi

    homedir=$HOME_MNT/$username
    if [ -e $homedir ]; then
	echo "Home directory already exists"
	exit 1
    fi

    # Create new user
    echo "Creating new user and group $username"
    useradd --user-group --create-home --home $homedir --shell /bin/bash $username

    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

    host_list=$username

else
    echo "Invalid username $username"
    exit 1
fi

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

        # Start client for host
	sudo -u $host -H gtermhost --daemon=restart --auth_file=$auth_file $host
    fi
done
