#!/bin/bash

set -e

. /etc/lsb-release
. /usr/lib/eole/ihm.sh
. /usr/lib/eole/utils.sh
#eolead.sh fournit CONTAINER_NAME, IP et ROOTFS
. /usr/lib/eole/eolead.sh

CACHE_DIR=/var/cache/lxc/${DISTRIB_CODENAME}
PARTIAL_DIR=${CACHE_DIR}/partial-amd64
SSH_EXEC="ssh -t -q -o LogLevel=ERROR -o StrictHostKeyChecking=no root@$CONTAINER_IP"

REALM=$(CreoleGet ad_domain)
WORKGROUP=$(CreoleGet ad_workgroup)
EOLE_MIRROR=$(CreoleGet serveur_maj | head -n 1)
DNS=$(CreoleGet adresse_ip_dns | head -n 1)
NTP=$(CreoleGet serveur_ntp)
NOM_CARTE=$(CreoleGet nom_carte_eth0)
GATEWAY=$(CreoleGet adresse_ip_gw)
CONTAINER_ETH0=$(CreoleGet ad_public_address)
CONTAINER_CIDR0=$(mask2cdr $(CreoleGet adresse_netmask_eth0))
EOLE_PROXY_ADDRESS=$(CreoleGet proxy_client_adresse '')
EOLE_PROXY_PORT=$(CreoleGet proxy_client_port '')
APT_PROXY_RES=$(apt-config shell APT_PROXY Acquire::http::Proxy)
eval ${APT_PROXY_RES}

# Do not use agent for connections in the container
unset SSH_AUTH_SOCK

# copied from diagnose/151-AD
IFS='.' read -a DN <<< $(CreoleGet ad_domain)
BASE_DN="DC=${DN[0]}"
for ((i=1;i<${#DN[@]};i++))
do
    BASE_DN="${BASE_DN},DC=${DN[$i]}"
done

echo
EchoBleu "Génération du conteneur $CONTAINER_NAME"

export DEBIAN_FRONTEND=noninteractive

# Use proxy from APT if not defined
if [ -z "${http_proxy}" ]
then
    if [ -n "${EOLE_PROXY_ADDRESS}" ]
    then
	export http_proxy="http://${EOLE_PROXY_ADDRESS}:${EOLE_PROXY_PORT}"
	export https_proxy="${http_proxy}"
    elif [ -n "${APT_PROXY}" ]
    then
	export http_proxy=${APT_PROXY}
	export https_proxy=${APT_PROXY}
    fi
fi

mkdir -p ${PARTIAL_DIR}/etc/apt/apt.conf.d
#We need Apt::Pipeline and No:Cache
cp /etc/apt/apt-eole.conf ${PARTIAL_DIR}/etc/apt/apt.conf
if [ -n "${http_proxy}" ]
then
    cat > ${PARTIAL_DIR}/etc/apt/apt.conf.d/02eoleproxy <<EOF
Acquire::http::Proxy "${http_proxy}";
Acquire::https::Proxy "${http_proxy}";
EOF
fi

# Réseau des conteneurs en 192.0.2.0/24
cat > /etc/default/lxc-net <<EOF
USE_LXC_BRIDGE="true"
LXC_BRIDGE="br0"
LXC_ADDR="192.0.2.1"
LXC_NETMASK="255.255.255.0"
LXC_NETWORK="192.0.2.0/24"
EOF

systemctl stop lxc-net
ip link del lxcbr0 2>/dev/null || true
sed -i 's/lxc.network.link.*/lxc.network.link = br0/' /etc/lxc/default.conf
systemctl start lxc-net

lxc-create -n $CONTAINER_NAME -t ubuntu -- -r $DISTRIB_CODENAME -u $DISTRIB_ID -S ~root/.ssh/id_rsa.pub --mirror http://$EOLE_MIRROR/ubuntu

# Workaround us keyboard set by lxc-create (#24385)
service keyboard-setup restart

echo
EchoBleu "Configuration du conteneur $CONTAINER_NAME"

# Configure keyboard
cp /etc/default/keyboard ${CONTAINER_ROOTFS}/etc/default/keyboard

# addc container in the master timezone #24933
cp /etc/timezone ${CONTAINER_ROOTFS}/etc/timezone
ln -nsf $(readlink /etc/localtime) ${CONTAINER_ROOTFS}/etc/localtime

[ ! -f /root/.ssh/id_rsa.pub ] && ssh-keygen -f /root/.ssh/id_rsa -N ''
mkdir -p $CONTAINER_ROOTFS/root/.ssh/
cp /root/.ssh/id_rsa.pub $CONTAINER_ROOTFS/root/.ssh/authorized_keys
chmod -R 600 $CONTAINER_ROOTFS/root/.ssh/

rm -f $CONTAINER_ROOTFS/etc/network/interfaces

chroot $CONTAINER_ROOTFS apt-get purge -y resolvconf
[ -L $CONTAINER_ROOTFS/etc/resolv.conf ] && rm -f $CONTAINER_ROOTFS/etc/resolv.conf
cat > $CONTAINER_ROOTFS/etc/resolv.conf <<EOF
nameserver $CONTAINER_ETH0
nameserver $DNS
search $REALM
EOF

# No dhcp interface in container
sed -ie 's/\(    eth0:\) {dhcp4: true}/\1{dhcp4: false}/' ${CONTAINER_ROOTFS}/etc/netplan/10-lxc.yaml

cat > /var/lib/lxc/$CONTAINER_NAME/config <<EOF
# Template used to create this container: /usr/share/lxc/templates/lxc-ubuntu

# Common configuration
lxc.include = /usr/share/lxc/config/ubuntu.common.conf

# Container specific configuration
lxc.uts.name = $CONTAINER_NAME
lxc.arch = amd64
lxc.rootfs.path = $CONTAINER_ROOTFS

# EOLE look for /dev/lxc to detect container mode and behave differently
lxc.tty.dir = LXC

# Automatic start at bootup
lxc.start.auto = 1

# Network configuration
# eth0 on eth0
lxc.net.0.type = macvlan
lxc.net.0.link = $NOM_CARTE
lxc.net.0.flags = up
lxc.net.0.name = eth0
lxc.net.0.mtu = 1500
lxc.net.0.macvlan.mode = bridge
lxc.net.0.ipv4.address = $CONTAINER_ETH0/$CONTAINER_CIDR0
lxc.net.0.ipv4.gateway = ${GATEWAY}

# containers on br0
# Reuse LTSP server IP
# http://eole.ac-dijon.fr/documentations/2.6/partielles/beta/EOLE/co/02-fichiers.html
lxc.net.1.type=veth
lxc.net.1.link=br0
lxc.net.1.flags=up
lxc.net.1.name = containers
lxc.net.1.mtu = 1500
lxc.net.1.veth.pair = ${CONTAINER_NAME}_0
lxc.net.1.ipv4.address = $CONTAINER_IP/24
EOF

cat > $CONTAINER_ROOTFS/etc/nsswitch.conf <<EOF
passwd:         compat winbind
group:          compat winbind
shadow:         compat
gshadow:        files

hosts:          files dns
networks:       files

protocols:      db files
services:       db files
ethers:         db files
rpc:            db files

netgroup:       nis
EOF

mkdir -p $CONTAINER_ROOTFS/etc/eole
cat > $CONTAINER_ROOTFS/etc/eole/samba4-vars.conf <<EOF
AD_REALM='$REALM'
AD_DOMAIN='$WORKGROUP'
AD_HOST_NAME='$CONTAINER_NAME'
AD_HOST_IP='$CONTAINER_ETH0'
NOM_CARTE_NIC1='eth0'
AD_SERVER_ROLE='controleur de domaine'
BASEDN='$BASE_DN'
NTP_SERVERS='$NTP'
AD_ADDITIONAL_DC_IP=''
AD_DOMAIN_SID=''
AD_ADDITIONAL_DC='non'
AD_DNS_BACKEND='SAMBA_INTERNAL'
AD_ADMIN='Administrator'
AD_HOST_KEYTAB_FILE='/var/lib/samba/eole-ad-dc.keytab'
ACTIVER_AD_HOMES_SHARE='oui'
ACTIVER_AD_PROFILES_SHARE='oui'
AD_HOMES_SHARE_HOST_NAME=''
AD_PROFILES_SHARE_HOST_NAME=''
AD_HOME_SHARE_PATH='/home/adhomes'
AD_PROFILE_SHARE_PATH='/home/adprofiles'
AD_INSTANCE_LOCK_FILE='/var/lib/samba/.instance_ok'
AD_BACKEND_STORE='tdb'
AD_PLAINTEXT_SECRETS='non'
EOF

mkdir -p $CONTAINER_ROOTFS/usr/lib/eole
cp /usr/lib/eole/ihm.sh $CONTAINER_ROOTFS/usr/lib/eole/ihm.sh
cp /usr/bin/tcpcheck $CONTAINER_ROOTFS/usr/bin/tcpcheck

ConfigureSourcesList $EOLE_MIRROR

echo
EchoBleu "Démarrage du conteneur $CONTAINER_NAME"
lxc-start -n $CONTAINER_NAME -d

try=0
max_try=10
while [ ${try} -le ${max_try} ]; do
    if [ ${try} -eq ${max_try} ]; then
        EchoRouge "Impossible de contacter le conteneur via ssh"
        exit 1
    fi
    sleep 2
    tcpcheck 3 $CONTAINER_IP:22 >/dev/null && break
    try=$((try+1))
done
echo -n "Serveur démarré : "
$SSH_EXEC "cat /etc/hostname"

echo
EchoBleu "Finalisation du conteneur $CONTAINER_NAME"

cat > $CONTAINER_ROOTFS/usr/sbin/policy-rc.d <<EOF
#!/bin/sh
exit 101
EOF
chmod a+x $CONTAINER_ROOTFS/usr/sbin/policy-rc.d


$SSH_EXEC "userdel -r Ubuntu 2>/dev/null"

$SSH_EXEC "apt-get update"
$SSH_EXEC "DEBIAN_FRONTEND=noninteractive apt-get install eole-ad-pkg -y"
$SSH_EXEC "apt-get clean"

cat > $CONTAINER_ROOTFS/etc/krb5.conf <<EOF
[libdefaults]
default_realm = ${REALM^^}
dns_lookup_realm = false
dns_lookup_kdc = false

[realms]
${REALM^^} = {
kdc = $CONTAINER_ETH0
}

[domain_realms]
.${REALM} = ${REALM^^}
${REALM} = ${REALM^^}
EOF

cat > $CONTAINER_ROOTFS/etc/samba/smb.conf <<EOF
[global]
  realm = ${REALM^^}
  workgroup = ${WORKGROUP^^}
  netbios name = ${CONTAINER_NAME^^}
  disable netbios = yes
  smb ports = 445
  vfs objects = acl_xattr
  map acl inherit = Yes
  store dos attributes = Yes
  winbind separator = /
  server role = active directory domain controller
  dns forwarder = $DNS
  tls enabled = yes
  tls keyfile = /var/lib/samba/private/tls/key.pem
  tls certfile = /var/lib/samba/private/tls/cert.pem
  tls cafile = /var/lib/samba/private/tls/ca.pem

[netlogon]
  comment = Network Logon Service
  path = /home/sysvol/$REALM/scripts
  read only = No
  guest ok = yes

[sysvol]
  comment = Sysvol Service
  path = /home/sysvol
  read only = No
  guest ok = yes

[homes]
  path = "/home/adhomes/%u"
  root preexec = /usr/share/eole/sbin/create_adhome.sh "%u" "/home/adhomes"
  comment = Home Directories
  read only = no
  invalid users = nobody guest

[profiles]
  comment = Profiles
  path = "/home/adprofiles"
  read only = No
  invalid users = nobody guest
EOF


echo
EchoBleu "Configuration du service samba-ad-dc"
$SSH_EXEC "systemctl mask smbd"
$SSH_EXEC "systemctl mask nmbd"
$SSH_EXEC "systemctl mask winbind"
$SSH_EXEC "systemctl unmask samba-ad-dc"
$SSH_EXEC "systemctl enable samba-ad-dc"

rm $CONTAINER_ROOTFS/usr/sbin/policy-rc.d

$SSH_EXEC ". /usr/lib/eole/samba4.sh && . /etc/eole/samba4-vars.conf && samba_instance"

cp $CONTAINER_ROOTFS/etc/krb5.conf $CONTAINER_ROOTFS/var/lib/samba/private/krb5.conf

[ ! -e /var/log/samba-ad-dc ] && ln -ns $CONTAINER_ROOTFS/var/log/samba /var/log/samba-ad-dc

# clean container cache
rm -rf ${CACHE_DIR}

echo
