#!/bin/sh -e

##########################################################################
#   Title:
#       Optional, defaults to the name of the script sans extention
#
#   Section:
#       8
#
#   Synopsis:
#       
#   Description:
#       Configure a FreeBSD or RHEL server to use KRB for sshd auth.
#       
#   Arguments:
#       KRB server ( may be an AD server )
#       
#   Returns:
#
#   Examples:
#
#   Files:
#
#   Environment:
#
#   See also:
#       
#   History:
#   Date        Name        Modification
#   2017?       Shawn Kwang Initial RHEL implementation
#   2018-05-14  Jason Bacon FreeBSD support
#   2024-11-12  Jason Bacon Add man page template and usage
##########################################################################

usage()
{
    cat << EOM

Usage: $0 <KRB-server>

Note: Active Directory servers may need to be specified in all CAPS.

EOM
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ $# != 1 ]; then
    usage
fi

server=$1

case $(auto-ostype) in
RHEL)
    yum -t install krb5-workstation pam_krb5 openldap-clients
    authconfig --enablekrb5 --krb5kdc=$server --krb5adminserver=$server \
	--krb5realm=$server --update
    ;;
    
FreeBSD)
    : ${PORTSDIR:=/usr/ports}
    # Ports require a specific version
    # Include not-yet-existent versions to kick the breakage can down the road
    ver=$(awk '$1 ~ "^DEFAULT_OPENLDAP_VER" { print $2 }' /usr/ports/Mk/bsd.ldap.mk)
    if [ -e $PORTSDIR/net/openldap$ver-client ]; then
	pkg install -y openldap24-client
	break
    fi

    # FIXME: Verify that this is valid and works correctly
    cp /etc/pam.d/xdm /etc/pam.d/xscreensaver
    
    # Sort of from here:
    # https://serverfault.com/questions/744918/ssh-kerberos-ad-how-where-to-config-etc-pam-d-password-auth
    for file in sshd system xdm; do
	sed -i '' -e '/pam_krb5.so/s|#auth|auth|' /etc/pam.d/$file
    done

    cat << EOM >> /etc/krb5.conf
[libdefaults]
    default_realm = $server
    dns_lookup_realm = true
    dns_lookup_kdc = true
    ticket_lifetime = 24h
    renew_lifetime = 7d
    forwardable = yes
EOM
    ;;

*)
    auto-unsupported-os $0
    exit 1
    ;;

esac
