#!/bin/bash
# ---------------------------------------------------------------------------
# makeuser - tilde new user creation
# Usage: makeuser [-h|--help] <username> <email> "<pubkey>"
# ---------------------------------------------------------------------------
#
# Forked from tilde.team's make user script (
PROGNAME=${0##*/}
VERSION="0.4"
LIST_NAME="thunix-join@lists.tildeverse.org"
ADMIN_EMAIL="root@thunix.net"
EMAIL_TEMPLATE="tmpl/email.tmpl"
YAML_FILE="$1.yml"

# Set location to your repo for ansible here
# It is only needed for thunix
REPO_LOCATION="/home/ubergeek/repos/ansible/"

error_exit() {
  echo -e "${PROGNAME}: ${1:-"Unknown Error"}" >&2
  exit 1
}

usage() {
  echo -e "usage: $PROGNAME [-h|--help] <username> <email> \"<pubkey>\""
}

sub_to_list() {
  echo "
From: $1
Subject: subscribe
" | sudo -u $1 mail $LIST_NAME 
}

[[ $(id -u) == 0 ]] && error_exit "Do not run this script as root."

case $1 in
  -h | --help)
    usage; exit ;;
  -* | --*)
    usage; error_exit "unknown option $1" ;;
  *)
    [[ $# -ne 3 ]] && error_exit "not enough args"
    echo "adding new user $1"
    newpw=`pwgen -1B 10`
    pwcrypt=$(perl -e "print crypt('${newpw}', 'sa');")
#    sudo useradd -m -g 1000 -p $pwcrypt -s /bin/bash $1 || exit 1
#		This is the welcome for team.
#    sed -e "s/newusername/$1/g" -e "s/newpassword/$newpw/" $EMAIL_TEMPLATE | sudo mail $1 $2 $ADMIN_EMAIL 

#		This is the welcome email for thunix
		sed -e "s/newusername/$1/g" -e "s/newpassword/$newpw/g" tmpl/email.tmpl | sudo mail -s "Welcome to Thunix!" $2
		sed -e "s/newusername/$1/g" -e "s/newpassword/$newpw/g" tmpl/email.tmpl | sudo mail -s "Welcome to Thunix!" $ADMIN_EMAIL 
    sub_to_list $1

#		We don't need this for thunix, since ansible will do it
#		echo "$3" | tee /home/$1/.ssh/authorized_keys

# If root doesn't have a fediverse account, comment this out
#    sudo toot "welcome new user ~$1!"

		;;
 
esac

