#!/bin/sh
# Pt-storage/src/compat-scripts/Pt-storage-adduser
# 
#  Copyright: ©2012, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
# This script is a simple command that we can use in support and refer to in our
# documentation to make it easy to add a user account for accessing the
# removable storage device.
#
# The script is run with one argument, which is the name of the user to add. It
# will ask for and confirm the password.
#
# This script can be maintained and kept compatible even when the broken set of
# user tools we currently have is replaced.
#

if [ $# -ne 1 ]
then
	cat <<EOF
Usage: $0 'new_username'

This command will create a new user that can be used for SFTP/rsync. When this
user connects, the storage will automatically be powered up and made available
under the directory /media/storage . When the user disconnects the storage will
be powered down. This can run in parallel with normal recording operation and
does not interfere with it.

The username should be a valid Unix username (in particular, no spaces!). A
password will be requested for the new user.
EOF
	exit 1
fi

NEW_USER="$1"



# abort on errors
set -e


# create the new user. gsl_adduser is pretty broken, as it doesn't let us
# set a shell and it only asks for a password once, meaning typos will happen.
# By pointing it at an empty stdin, it leaves the account without a valid
# password, so nobody can login.
echo "" | gsl_adduser -a "${NEW_USER}"


# now set a password for the user; this does the standard "ask twice"
# process to avoid typos.
passwd "${NEW_USER}"


# now we compensate for Pt-user-admin's lack of chsh
sed -i /etc/passwd \
	-e 's,^'${NEW_USER}':\(.*\):/bin/bash,'${NEW_USER}':\1:/usr/bin/Pt-storage-login,'


# now we compensate for Pt-user-admin's lack of any utility to safely
# modify the group file. We have to cope with modifying an empty group
# line and a group line with existing entries separately.
if grep -q '^mstorage:x:154:$' /etc/group
then
	sed -i /etc/group \
		-e 's/^mstorage:x:154:$/mstorage:x:154:'${NEW_USER}'/'
else
	sed -i /etc/group \
		-e 's/^mstorage:x:154:\(..*\)$/mstorage:x:154:'${NEW_USER}',\1/'
fi


echo "New user '${NEW_USER}' added and ready."
