#!/bin/sh

HOME_BASE="/app/python_app/modules"
USERS_LIST="/app/config/users.txt"
PASSWD_LIST="/app/config/passwords.txt"
CUSTOM_SCRIPT="/app/config/init.sh"

separator="=" # Must be ascii for cut
forbidden_chars=". / : # = \ "

# Check we got user list
if [ ! -f "$USERS_LIST" ] && [ ! -f "$PASSWD_LIST" ] ; then
    echo "Les fichiers des utilisateurs ou des passwords n’ont pas étés trouvées."
    exit 1
fi

for c in $forbidden_chars ; do
    if [ -n "$(cat "$USERS_LIST" | grep -F $c)" ] ; then
        echo "Le fichier « $USERS_LIST » ne doit pas contenir le caractère « $c » !"
        exit 1
    fi
done

# Generate passwords if not done yet
genPassowrd () {
    tr -dc A-Za-z0-9 </dev/urandom | head -c $1
}
for user in $(cat "$USERS_LIST") ; do
    if [ -z "$user" ] || [ -n "$(cat $PASSWD_LIST | grep "$user$separator")" ] ; then continue ; fi
    echo "$user$separator$(genPassowrd 10)" >> $PASSWD_LIST
done

# Create users, home dirs, change passwords and home owners
for line in $(cat $PASSWD_LIST) ; do
    name="$(echo "$line" | cut -d "$separator" -f 1)"
    pass="$(echo "$line" | cut -d "$separator" -f 2)"
    if [ -z "$name" ] || [ -z "$pass" ] ; then echo "Malformed line skipped: '$line'" ; continue ; fi
    home="$HOME_BASE/$name"
    mkdir -p "$home"
    useradd --home-dir "$home" --no-user-group -G eleve --shell /bin/bash "$name"
    $ret="$?"
    if [ "$ret" -ne 0 ] && [ "$ret" -ne 9 ] ; then
        echo "Can’t create user '$name'. Error '$ret'."
        continue
    fi
    echo "$pass\n$pass" | passwd "$name" &> /dev/null
    chown "$name":eleve "$home"
done


echo "\nFin de la préparation des utilisateurs.\n"

# Custom script
if [ -f "$CUSTOM_SCRIPT" ] ; then
    if [ ! -x "$CUSTOM_SCRIPT" ] ; then
        chmod +x "$CUSTOM_SCRIPT"
    fi
    "$CUSTOM_SCRIPT"
fi

# Nginx
nginx -c '/etc/nginx/nginx.conf'

# SSH server
/usr/sbin/sshd -E /dev/stderr

# Start watever the container should be doing
/bin/sh -c "$*" &
pid="$!"
trap "kill -INT  $pid" INT
trap "kill -TERM $pid" TERM
wait "$pid"
