#!/bin/bash

############################################################
GEN=tc8                          # TC Generation/Name prefix
OUD="Компьютеры - ZMB"           # TC placement default OU
############################################################
IAM=$(readlink -e $0)            # /opt/zmb-setup/zmb-setup
SVC=$(basename $IAM)             # zmb-setup
LOG=/var/log/$SVC                # /var/log/zmb-setup
URL=http://$(<$IAM.server)/setup # Release and Reports URL
############################################################
TTY=/etc/systemd/system/getty@.service.d
############################################################
export LANG=en_US.UTF-8          # Try to Speak in English
dmesg --console-off              # Disable Kernel messages
############################################################

_adjoin()
{

[ -z "$SSH_CLIENT$SSH_CONNECTION" ] && clear

while [ -d $TTY ]
do
  source /etc/os-release

  echo
  echo "Hostname: $(hostnamectl --static)"
  echo "Datetime: $(date +%d.%m.%Y\ %T\ UTC\ %z)"
  read -p "Username: "

  kinit "$REPLY" && \
    net ads join --no-dns-updates -k osName="$NAME" osVer="$VERSION" osServicePack="$(</etc/zmb-release)" createcomputer="$OUD" && \
      rm -rf $TTY && systemctl daemon-reload

  kdestroy
done

chvt 1 &> /dev/null

}

_main()
{

#
# swap file
#
if dd if=/dev/zero of=/swap bs=1M count=2048
then
  chmod  -v 0600 /swap
  mkswap -f      /swap
  swapon -v      /swap
  grep "^/swap " /etc/fstab || echo "/swap swap swap defaults 0 0" >> /etc/fstab
fi

#
# zmb-release
#
while ! dnf --nodocs \
            --noplugins \
            --setopt install_weak_deps=false \
            --setopt reposdir=/dev/null \
            --assumeyes \
            --nogpgcheck \
            install $URL/zmb-release.rpm
do
  sleep 5
done

#
# zmb, zmb-ad
#
while ! dnf --assumeyes --config /opt/zmb/dnf/dnf.conf --refresh install zmb zmb-ad
do
  sleep 5
done

systemctl --now disable chronyd oddjobd sssd

#
# ad fqdn
#
DNS=$(grep "realm" /opt/zmb/smb/smb.conf | cut -s -d = -f 2 | \
      awk '{print tolower($1)}')

#
# chrony
#
timedatectl set-local-rtc 0
sed -i "s/^pool .*/pool $DNS iburst/g;s/^server .*/server $DNS iburst/g" /etc/chrony.conf
systemctl --now enable chronyd

#
# hostname
#
for i in $(ls -1 /sys/class/net)
do
  [ "$i" = "lo" ] || hostnamectl set-hostname $GEN$(sed "s/://g" /sys/class/net/$i/address).$DNS
  [ -z $(nmcli --mode multiline --fields DHCP4 device show $i | grep " ip_address = " | awk '{print $4}') ] || break
done

#
# "zmb-setup" user
#
useradd --home-dir /dev/shm \
        --gid 0 \
        --key MAIL_DIR=/dev/null \
        --no-create-home \
        --non-unique \
        --shell $IAM \
        --uid 0 \
        $SVC &> /dev/null

mkdir -pv $TTY
cat   >   $TTY/override.conf << EOF
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin $SVC %I \$TERM
EOF
systemctl daemon-reload

curl --head $URL/$SVC:1 &> /dev/null

#
# zmb-basic packages
#
[ -f /opt/zmb/bin/zmb.exit ] && /opt/zmb/bin/zmb

#
# waiting for domain joined
#
cat << EOF

*************************************************************
*                                                           *
*  The Managed Box (ZMB) is ready to Active Directory join  *
*                                                           *
*               Press Ctrl-Alt-F2 to continue               *
*                                                           *
*************************************************************

EOF

echo -n "Waiting for domain joined"
while [ -d $TTY ]
do
  echo -n "."; sleep 1
done
echo " done"

#
# the end
#
curl --head $URL/$SVC:2 &> /dev/null

shutdown --poweroff 1

authselect select sssd with-mkhomedir --force
systemctl enable oddjobd sssd /opt/zmb/bin/zmb.service
systemctl set-default graphical.target

for c in $(nmcli --terse --fields UUID connection show --active)
do
  nmcli connection down $c
done
systemctl stop NetworkManager
rm -rfv /var/lib/NetworkManager/*

systemctl disable $SVC
userdel -f $SVC

echo -n "The Managed Box (ZMB) Setup is complete, wait for shutdown"
bash -c "while true; do echo -n '.'; sleep 1; done" &

rm -rf $(dirname $IAM)

}

if tty -s || [ -n "$SSH_CLIENT$SSH_CONNECTION" ]
then
  _adjoin
else
  _main 2>&1 | tee -a /dev/console $LOG
fi
