#!/bin/bash



####################################
# NOTE: There is currently no
#       support for host-based
#       system-user definitions
#
# WARNING: There is no support for
#          removing created users!
####################################



### Include ymclibnettools
. /usr/lib/lib-fliwi/ymc-networktools.bash

if [ $(ymc_is_chroot) -ne 0 ]; then
  echo "WARNING: $0 can not be run inside a chroot..."
  exit 0
fi

ymc_user_exists()
{
  temp_user_to_check=$1
  current_system_users=$(cat /etc/passwd | cut -d ':' -f 1)
  ymc_contains "$temp_user_to_check" $current_system_users
  return $?
}


ymcScriptName=$(basename $0)


### handle service-based system-users
for my_service in $(fliwi-get-my-services)
do
  for system_user_name in $(fliwi-get-system-users -s --show-name $my_service)
  do
    echo "INFO: Processing system-user '$system_user_name' for services '$my_service'..."
    system_user_uid=$(fliwi-get-system-users -s --show-uid --limit=$system_user_name $my_service) && \
    system_user_shell=$(fliwi-get-system-users -s --show-shell --limit=$system_user_name $my_service)  && \
    system_user_home=$(fliwi-get-system-users -s --show-home --limit=$system_user_name $my_service) || false
    if [ $? -ne 0 ] || \
       [ "$system_user_uid" == "" ] || \
       [ "$system_user_shell" == "" ] || \
       [ "$system_user_home" == "" ]; then
      echo "ERROR: Can not get all required system-user-definition from cluster-config for system-user '$system_user_name' of services '$my_service' - skipping"
      continue
    fi

    if [ $(ymc_user_exists $system_user_name) -ne 0 ]; then
      echo "INFO: System-user '$system_user_name' already exists - skipping..."
      continue
    fi

    /usr/sbin/adduser --system --group --disabled-password --disabled-login --no-create-home \
                      --gecos $my_service','$ymcScriptName \
                      --shell "$system_user_shell" \
                      --home "$system_user_home" \
                      --uid $system_user_uid \
                      $system_user_name
    if [ $? -eq 0 ]; then
      echo "INFO: Added system-user '$system_user_name' with uid #$system_user_uid, shell '$system_user_shell' and home-dir '$system_user_home'"
    else
      echo "WARNING: Failed to add  system-user '$system_user_name' with uid #$system_user_uid, shell '$system_user_shell' and home-dir '$system_user_home' - skipping..."
      continue
    fi
  done
done


exit 0
