#!/bin/bash
#Common functions used for several makeuser scripts

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 
}

makeuser_no_ansible()
{
	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" include/email.tmpl | sudo mail -s "Welcome to Thunix!" $2,$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!"
}

add_account_recovery()
{	
	sudo mkdir -p --mode=700 /home/$1/.thunix
	echo $2 | sudo tee /home/$1/.thunix/recovery
	sudo chmod 600 /home/$1/.thunix/recovery
	sudo chown -R $1 /home/$1/.thunix
}

remove_user()
{
  echo "Unsubscribe from this list..."
  echo "From: $1 Subject: unsubscribe " | sudo -u $1 mail $LIST_NAME 

  echo "Deleting account from system..."
  sudo userdel $1
  sudo rm -rf /home/$1

  echo "$1 user account is unenforced in ansible..."
  currdir=`pwd`
  cd $REPO_LOCATION; git pull
  sed -i "/$1/d" $REPO_LOCATION/roles/shell/tasks/users.yml
  rm $REPO_LOCATION/roles/shell/tasks/users/$YAML_FILE
  git commit -am "$1 account unenforced in ansible"
  git push
  cd $currdir

  echo "User $1 removed from system." | sudo mail -s "User Account $1 removed from Thunix" $ADMIN_EMAIL
}

backup_user_data()
{
  echo "Archiving home dir..."
  sudo tar cfz $BACKUP_USER_DATA/$1.tgz /home/$1
}

#Common functions used for Databases management scripts

database_create()
{
sudo mysql -u root << _EOF
CREATE DATABASE $DATABASE;
GRANT ALL PRIVILEGES ON $DATABASE.* TO '$USER'@'localhost' IDENTIFIED BY '$PASSWORD';
FLUSH PRIVILEGES;
_EOF
}

database_backup()
{
  sudo mysqldump -u root $DATABASE | gzip > /tmp/$DATABASE.sql.gz
  sudo mv /tmp/$DATABASE.sql.gz $BACKUP_USER_DATA/
}

database_remove()
{
sudo mysql -u root << _EOF
DROP DATABASE $DATABASE;
FLUSH PRIVILEGES;
_EOF
}
