#!/bin/bash

#set -e

. /etc/lsb-release
. /usr/lib/eole/ihm.sh

CONTAINER_NAME=addc
CONTAINER_IP=192.0.2.2
CONTAINER_ROOTFS=/var/lib/lxc/$CONTAINER_NAME/rootfs
EOLE_MIRROR=test-eole.ac-dijon.fr
SSH_EXEC="ssh -t -q -o LogLevel=ERROR -o StrictHostKeyChecking=no root@$CONTAINER_IP"
PACKAGES="samba samba-dsdb-modules samba-vfs-modules ldb-tools krb5-user smbclient cifs-utils libnss-winbind eole-resolvconf"

EchoOrange "Ce programme va installer et configurer le service samba-ad-dc dans le conteneur $CONTAINER_NAME."
echo
Question_ouinon "Continuer"
[ $? -ne 0 ] && exit 0

echo "Adresse du service samba-ad-dc sur le réseau pédagogique"
echo "(Adresse IP libre située dans la même plage que celle du module Scribe $(CreoleGet adresse_ip_eth0))"
read CONTAINER_ETH0

DOMAINE=$(CreoleGet nom_domaine_local)
DNS=$(CreoleGet adresse_ip_dns | head -n 1)
NTP=$(CreoleGet serveur_ntp)

echo
EchoBleu "Vérification des dépendances"
apt-eole install lxc1 lxc-templates debootstrap cgroup-lite

echo
EchoBleu "Génération du conteneur $CONTAINER_NAME"
export DEBIAN_FRONTEND=noninteractive
#lxc-create -n $CONTAINER_NAME -t ubuntu -- -r $DISTRIB_CODENAME -u $DISTRIB_ID -S ~root/.ssh/id_rsa.pub --packages $PACKAGES --mirror http://$EOLE_MIRROR/ubuntu
lxc-create -n $CONTAINER_NAME -t ubuntu -- -r $DISTRIB_CODENAME -u $DISTRIB_ID -S ~root/.ssh/id_rsa.pub --mirror http://$EOLE_MIRROR/ubuntu

echo
EchoBleu "Configuration du conteneur $CONTAINER_NAME"

[ ! -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/

# 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"
LXC_DHCP_RANGE="192.0.2.198,192.0.2.199"
EOF

systemctl restart lxc-net

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.utsname = $CONTAINER_NAME
lxc.arch = amd64
lxc.rootfs.backend = dir
lxc.rootfs = $CONTAINER_ROOTFS

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

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

# Network configuration
# eth0 on eth0
lxc.network.type = macvlan
lxc.network.link = ens4
lxc.network.flags = up
lxc.network.name = eth0
lxc.network.mtu = 1500
lxc.network.macvlan.mode = bridge
lxc.network.ipv4 = $CONTAINER_ETH0/24

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

cat > $CONTAINER_ROOTFS/etc/krb5.conf <<EOF
[libdefaults]
   default_realm = ${DOMAINE^^}
   dns_lookup_realm = true
   dns_lookup_kdc = true
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='$DOMAINE'
AD_DOMAIN='$(echo $DOMAINE|cut -d'.' -f1)'
AD_HOST_NAME='$CONTAINER_NAME'
AD_HOST_IP='$CONTAINER_ETH0'
NOM_CARTE_NIC1='eth0'
AD_SERVER_ROLE='controleur de domaine'
NTP_SERVERS='$NTP'
AD_ADDITIONAL_DC_IP=''
AD_DOMAIN_SID=''
AD_ADDITIONAL_DC='non'
AD_DNS_BACKEND='SAMBA_INTERNAL'
AD_ADMIN='Administrator'
AD_ADMIN_PASSWORD_FILE='/var/lib/samba/.eole-ad-dc'
AD_HOST_KEYTAB_FILE='/var/lib/samba/eole-ad-dc.keytab'
ACTIVER_AD_HOMES_SHARE='non'
ACTIVER_AD_PROFILES_SHARE='non'
AD_HOMES_SHARE_HOST_NAME='file'
AD_PROFILES_SHARE_HOST_NAME='file'
AD_HOME_SHARE_PATH='/home/adhomes'
AD_PROFILE_SHARE_PATH='/home/adprofiles'
AD_INSTANCE_LOCK_FILE='/var/lib/samba/.instance_ok'
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
wget "https://dev-eole.ac-dijon.fr/gitweb/eole-ad-dc?p=eole-ad-dc.git;a=blob_plain;f=lib/eole/samba4.sh;hb=refs/heads/2.6.2/master" -O $CONTAINER_ROOTFS/usr/lib/eole/samba4.sh
# FIXME : hostnamectl hack
sed -ie 's/ hostnamectl/ #hostnamectl/' $CONTAINER_ROOTFS/usr/lib/eole/samba4.sh
wget "https://dev-eole.ac-dijon.fr/gitweb/eole-ad-dc?p=eole-ad-dc.git;a=blob_plain;f=scripts/validSambaPassword;hb=refs/heads/2.6.2/master" -O $CONTAINER_ROOTFS/usr/sbin/validSambaPassword
chmod u+x $CONTAINER_ROOTFS/usr/sbin/validSambaPassword

grep -iv envole /etc/apt/sources.list > $CONTAINER_ROOTFS/etc/apt/sources.list
cp /etc/apt/trusted.gpg.d/eole-archive-keyring.gpg $CONTAINER_ROOTFS/etc/apt/trusted.gpg.d/eole-archive-keyring.gpg
cat > $CONTAINER_ROOTFS/etc/apt/sources.list.d/seth-samba.list <<EOF
deb http://$EOLE_MIRROR/samba samba-4.7 main
EOF

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
    [ $? -eq 0 ] && break
    try=$((try+1))
done
echo -n "Serveur démarré : "
$SSH_EXEC "cat /etc/hostname"

echo
EchoBleu "Finalisation du conteneur $CONTAINER_NAME"
$SSH_EXEC "apt-get update"

$SSH_EXEC "DEBIAN_FRONTEND=noninteractive apt-get install $PACKAGES -y"
$SSH_EXEC "apt-get clean"

cat > $CONTAINER_ROOTFS/etc/samba/smb.conf <<EOF
[global]
  realm = ${DOMAINE^^}
  workgroup = $(echo ${DOMAINE^^}|cut -d'.' -f1)
  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/$DOMAINE/scripts
  read only = No
  guest ok = yes

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

[ -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 $DOMAINE
EOF

echo
EchoBleu "Configuration du service samba-ad-dc"
$SSH_EXEC "systemctl enable samba-ad-dc"
$SSH_EXEC ". /usr/lib/eole/samba4.sh && . /etc/eole/samba4-vars.conf && samba_instance"

echo
