#!/bin/bash

#Version:      @(#)make_users.sh  1.2  2019-08-13  joerg.reinholz@fastix.org
#Licence:      show https://code.fastix.org/lizenz.php

# Konfiguration:
source `dirname $0`/make_del_users.settings;

# Löschen der alten Benutzer
source `dirname $0`/del_users.sh;

if [ -f "$outFile" ]; then
	truncate -s0 "$outFile";
fi

i=1;
end=$(($users+1));
sql="SET NAMES 'utf8';";

while [ $i -lt $end ]; do
	if [ $i -lt 10 ]; then
		username="tn0$i";
	else
		username="tn$i";
	fi
	# Als Passwort nehmen wor einfach einen Teil des zufälligen Salts:
	password=`mkpasswd -m sha-512 PASSWORD | cut -b 4-12`;

	# Bauen des Password-Hashes:
	passwordHash=`mkpasswd -m sha-512 $password`;

	# Benutzer hinzufügen:
	useradd -m -s "/bin/bash" --password "$passwordHash" "$username";
	if [ "" != "$extraGroups" ]; then
		usermod -aG "$extraGroups" $username;
	fi

	# Datenbank und Datenbankzugang mit gleichen Daten hinzufügen (Befehle sammeln)
	if [ 1 -eq $hasMySQL ]; then
		s="CREATE DATABASE $username; GRANT ALL ON $username.* TO '$username'@'%' IDENTIFIED BY '$password';";
		sql="$sql $s";
	fi
	echo "" >> "$outFile";
	echo "$username    $password" >> "$outFile";
	echo "" >> "$outFile";
	echo "--------------------------------------------" >> "$outFile";
	i=$(($i+1));
done

# Datenbank und Datenbankzugang mit gleichen Daten hinzufügen (exec)
if [ "" != "$sql" ]; then
	if [ "" == "$dbrootpw" ]; then
		echo "$sql" | mysql -u root;
	else
		echo "$sql" | mysql -u root --password="$dbrootpw";
	fi
fi

less "$outFile";
echo "    Benutzer-Password-Datei ist: \"$outFile\". Sie können diese mit";
echo "    lp \"$outFile\"";
echo "    drucken.";