#!/bin/bash
set -e

# check for root
if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root" 1>&2
  exit 1
fi

# check for arguments
if [[ $# -ne 1 ]]; then
  echo "USAGE: $0 username" 1>&2
  exit 1
fi

# check if user already exists
if ! id "$1" &> /dev/null; then
  echo "Adding user..."
  useradd --base-dir /home --create-home "$1"
fi

# check if SSH key for user already exists
if [[ ! -f "/home/$1/.ssh/id_ecdsa" ]]; then
  echo "Generating SSH key for user..."
  sudo --user "$1" ssh-keygen -t ecdsa -N "" -b 521 -f "/home/$1/.ssh/id_ecdsa" > /dev/null
fi

# check if SSH key is already added to list of authorized keys
sudo -u "$1" touch /home/$1/.ssh/authorized_keys
if ! grep -q "`cat /home/$1/.ssh/id_ecdsa.pub`" /home/$1/.ssh/authorized_keys; then
  echo "Adding SSH key to list of authorized keys for user..."
  cat "/home/$1/.ssh/id_ecdsa.pub" | sudo --user "$1" tee "/home/$1/.ssh/authorized_keys" > /dev/null
fi

export DIR="`mktemp -d`"
trap "cd /; rm -rf $DIR" EXIT
cd "$DIR"
export GIT_AUTHOR_NAME=$SUDO_USER
git clone "git@zotac0:gitolite-admin" "$DIR" > /dev/null

# check if SSH key is already registered with git
if [[ ! -f "$DIR/keydir/$1@$HOSTNAME.pub" ]]; then
  echo "Adding SSH key to git..."
  cp "/home/$1/.ssh/id_ecdsa.pub" "$DIR/keydir/$1@$HOSTNAME.pub"
  git add "$DIR/keydir/$1@$HOSTNAME.pub"
  git commit --all --message="User \"$1\" added" > /dev/null
  git push > /dev/null
fi
