#!/bin/sh
#
# Configure machine for roaming, ie disconnected operation.

set -e

bindir=$(dirname $0)

append_if_missing() {
    file="$1"
    string="$2"
    if [ -e "$file" ] ; then
        if ! grep -qxF "$string" "$file" ; then
            echo "$string" >> $file
        fi
    fi
}

DEBIAN_FRONTEND=noninteractive
export DEBIAN_FRONTEND

# Make sure the packages we need are installed
apt-get install -y host ldap-utils

aptitude install -y libpam-mklocaluser
aptitude install -y libpam-sss libnss-sss

# Make sure the NSS module refered below always is installed
aptitude install -y libnss-myhostname libnss-mdns libnss-ldapd

# Avoid duplicate pam setup, remove the non-caching ldapd version
apt-get purge -y libpam-ldapd

# Avoid duplicate pam setup, remove the non-caching kerberos version too
apt-get purge -y libpam-krb5

# Avoid double caching, as sssd is already caching
apt-get purge -y nscd

# Roaming workstations are typically single user machines, so do not
# throw out the user if he is idle.
apt-get purge -y killer

# configure sssd
rm -f /etc/sssd/sssd.conf
$bindir/sssd-generate-config > /etc/sssd/sssd.conf
if [ -s /etc/sssd/sssd.conf ] ; then
    chmod 600 /etc/sssd/sssd.conf
    chown root:root /etc/sssd/sssd.conf
else # Fallback failed, link to static setup
    # sssd refuses to read the file if it has any other mode
    chmod 600 /etc/sssd/sssd-debian-edu.conf
    chown root:root /etc/sssd/sssd-debian-edu.conf
    rm -f /etc/sssd/sssd.conf
    ln -s sssd-debian-edu.conf /etc/sssd/sssd.conf
fi
invoke-rc.d sssd restart || true

# try to set up kerberos
if $bindir/sssd-generate-config -k > /etc/krb5.conf.new ; then
    chmod 644 /etc/krb5.conf.new
    mv /etc/krb5.conf.new /etc/krb5.conf
else
    rm /etc/krb5.conf.new
fi

# FIXME See if we can drop libnss-ldapd now that sssd support sudoers. (compatible LDAP schema?)
# FIXME See if we can drop libnss-ldapd even if sssd do not support networks
# This code is still needed even thought sssd since version 1.2-2
# update nsswitch.conf during installation, because we want to disable
# ldap and enable sss for only some of the tables.
cat > /etc/nsswitch.conf <<'EOF'
# /etc/nsswitch.conf
#
# Example configuration of GNU Name Service Switch functionality.
# If you have the `glibc-doc-reference' and `info' packages installed, try:
# `info libc "Name Service Switch"' for information about this file.

passwd:         files sss
group:          files sss
shadow:         files sss

hosts:          files myhostname mdns4_minimal [NOTFOUND=return] dns mdns4
networks:       files ldap

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

netgroup:       files sss
sudoers:        files ldap
EOF
