#!/bin/bash -e

# usage message
usage() {
	echo "
Add user and configure hasher and gear for him/her
Usage:
$(basename ${0}) <user name>
Add and configure <user name>
$(basename ${0}) --help
Print this message
"
}

addifnot() {
# Add string to file if this string is not in the file
# Usage: addifnot <string> <file>

if [ -z "$1" -o -z "$2" ]
then
	echo "Error: Function addifnot requires two arguments: addifnot <string> <file>"
	return 1
fi

if [ -f "$2" -a ! -w "$2" ]
then
	echo "Error: addifnot: File $2 is not writable"
	return 1
fi

grep $1 $2 >&/dev/null || echo $1 >> $2
}

if [ "$1" == "--help" ]
then
	usage
	exit 0
fi

# name for builder user
if [ $# -gt 0 ]
then
	USER=$1
else
	echo "Error: This script requires at least one argument."
	usage
	exit 1
fi

# ensure sudo user
if [ "$(whoami)" != "root" ]
then
	echo "Error: This script requires 'sudo' privileges in order to add user."
	exit 1
fi

ARCH="$(rpm --eval '%_host_cpu')"

# if useradd exit code 9 then this $USER already has a password
USRADDEX=0
useradd -m "$USER" || USRADDEX=$?
if [ $USRADDEX -eq 0 ]
then
	passwd "$USER"
else
	[ $USRADDEX -eq 9 ] || exit 1
fi

# ~
HOME="/home/$USER"
install -dm750 -o "$USER" -g "$USER" "$HOME"

# http://altlinux.org/tmpfs
TMP="/tmp/.private/$USER"

su - -c "git config --global user.email $USER@localhost" "$USER"
su - -c "git config --global user.name $USER" "$USER"

# rpm
sed -i '/^%_tmppath.*tmp$/d' "$HOME/.rpmmacros"
cat << EOF >> "$HOME/.rpmmacros"
%packager       $USER <$USER@altlinux.org>
%_target_cpu    $ARCH
%_tmppath       $TMP
%_sourcedir     %{_topsrcdir}/SOURCES/%name
EOF

# hasher
if [ "$ARCH" != i586 -a "$ARCH" != x86_64 -a "$ARCH" != e2k ]
then
        # Not enough space on tmpfs
        WORKDIR="$HOME/hasher"
else
        WORKDIR="$TMP/hasher"
        ln -s "$WORKDIR" "$HOME/hasher"
fi
addifnot "rpm-dir file://$HOME/hasher/repo $ARCH hasher" \
"/etc/apt/sources.list.d/hasher.list" || exit 1

mkdir "$HOME/.hasher"
cat >> "$HOME/.hasher/config" << EOF
packager="\$(rpm --eval %packager)"
def_target=$ARCH
export GCC_USE_CCACHE=1
mkdir -p "$WORKDIR"
EOF

# squashfs-tools 4.3+
addifnot "allowed_mountpoints=/proc" "/etc/hasher-priv/system" || exit 1

# need to increase the limits
addifnot "wlimit_time_elapsed=21600" "/etc/hasher-priv/system" || exit 1
addifnot "wlimit_time_idle=21600" "/etc/hasher-priv/system" || exit 1

# requisite
hasher-useradd "$USER" >&/dev/null
