#!/usr/bin/bash
# 
# IMPORTANT NOTE: registering a host in the ESO ADS domain requires to have 
#                 access (password) to an adminstrative account at the server
#                 e.g. "joindomain". You get the password for "joindomain" by
#                 request to "David.Bargna@eso.org"
# Useful command to enquire the AD server:
#   ldapsearch -h ads.eso.org -x -D <AD user> \
#   -W "(dNSHostName=$HOSTNAME)" distinguishedName # (1)
#   (1) ldapsearch is provided with openldap-clients RPM

# Main, main
startdir=$PWD
cmd=`basename $0`
basedir=`dirname $0`

grep -q AlmaLinux /etc/redhat-release
ISFEDORA=$?

if [ `whoami` != "root" ]; then
  echo "Error: You need to be root to run $cmd"
  echo "Usage: $cmd [--verbose]"
  exit 1
fi

if ! rpm -q realmd ; then
  echo "Installing RPM realmd"
  yum -y install realmd
fi

if ! rpm -q oddjob-mkhomedir ; then
  echo "Installing RPM oddjob-mkhomedir"
  yum -y install oddjob-mkhomedir
fi

if ! rpm -q adcli ; then
  echo "Installing RPM adcli"
  yum -y install adcli
fi

# first, to enable support for the RC4 cipher, you need to run the following command and restart:

if [ $ISFEDORA -eq 1 ]; then
  update-crypto-policies --set DEFAULT:AD-SUPPORT >/dev/null 2>&1
else
  update-crypto-policies --set DEFAULT:AD-SUPPORT-LEGACY >/dev/null 2>&1
fi

 # Register as "joindomain" user. Ask IT for the password.
#set -x
if [ $ISFEDORA -eq 1 ]; then
  realm join $1 --user=joindomain ads.eso.org --automatic-id-mapping=no --os-name=Fedora --os-version=40 --computer-ou="ou=Linux,ou=Servers,ou=Garching,ou=New Structure,dc=ads,dc=eso,dc=org"
else
  realm join $1 --user=joindomain ads.eso.org --automatic-id-mapping=no --os-name=AlmaLinux --os-version=10 --computer-ou="ou=Linux,ou=Servers,ou=Garching,ou=New Structure,dc=ads,dc=eso,dc=org"
fi

if [ $? -eq 1 ]; then
  echo "This host already registered"
  echo "To unregister, execute: \"realm leave --verbose ads.eso.org\""
  exit 1
fi
if [ $? -ne 0 ]; then
  echo "Error. Try running again as \"elt-enable-ads --verbose\""
  exit 1
fi

#If the host is already registered in AD you can omit the "--computer-ou" option, as it will give an error.

# Modify the following settings, to allow users to log in without having to prefix "ads\" to their username:

sed -i 's/use_fully_qualified_names = True/use_fully_qualified_names = False/' /etc/sssd/sssd.conf

sed -i 's/fallback_homedir = \/home\/%u@%d/fallback_homedir = \/home\/%u/' /etc/sssd/sssd.conf

systemctl restart sssd

# To automatically mount the unix home directories (nfs shares) on the server when the users log in:
if [ ! -f /etc/auto.unix ]; then
  echo "* -fstype=nfs,rw,nosuid homehost.hq.eso.org:/vol/home/&" > /etc/auto.unix
fi
if ! egrep -q "^/home" /etc/auto.master ; then
  echo "/home	/etc/auto.unix	nfsvers=3" >> /etc/auto.master
fi

systemctl enable --now autofs

# Initiate ADS login services
echo "IMPORTANT !!!!"
echo "Change root password !!!!"
exit 0
