#!/bin/bash
LOG_FILE="/var/log/userdata-workstations.log"

# Bind LUKS to TPM2 chip
ENC_PART=$(blkid -t TYPE=crypto_LUKS | awk -F: '{ print $1 }')
PASSWORD="FleetAtPingLinuxEncryption"
STR="${PASSWORD}\n"
echo -e $STR | clevis luks bind -d $ENC_PART tpm2 '{"pcr_bank":"sha256"}'
update-initramfs -u -k all

# Change LUKS password
NEWPASSWORD=$(dmidecode -s system-uuid)
STR="${PASSWORD}\n${NEWPASSWORD}\n${NEWPASSWORD}\n"
echo -e $STR | cryptsetup luksChangeKey $ENC_PART

# Set hostname
NEW_HOSTNAME="lnx-$(dmidecode -s system-serial-number)"
sed -i "s/$(hostname)/$NEW_HOSTNAME/g" /etc/hosts
hostnamectl hostname $NEW_HOSTNAME --transient --static

# Set password requirements
sed -i 's/^PASS_MAX_DAYS.*/PASS_MAX_DAYS   99999/' /etc/login.defs
sed -i '1s/^/password requisite pam_pwquality.so retry=3 minlen=15 remember=10 enforcing=1\n/' /etc/pam.d/common-password

# Logon Screen legal message
# sed -i 's/^#WaylandEnable=.*/WaylandEnable=false/' /etc/gdm3/custom.conf 
sed -i 's/^# banner-message-enable.*/banner-message-enable=true/' /etc/gdm3/greeter.dconf-defaults
sed -i "s/^# banner-message-text.*/banner-message-text='This notice is subject to applicable law. You are about to access Ping Identitys computer systems that are intended for authorized users only. You should have no expectation of privacy in your use of Ping systems. Use of Ping systems constitutes consent to monitoring, retrieval, and disclosure of any information stored within the systems for any purpose, including criminal prosecution. For questions contact helpdesk@pingidentity.com or 1-720-508-8338.'/" /etc/gdm3/greeter.dconf-defaults

# Force user to change password on first login
passwd -e $(id -nu 1000)

#Create /opt/ directory
mkdir -p "/opt/ping"

# Install network-manager-l2tp and network-manager-l2tp-gnome
sudo apt install -y network-manager-l2tp network-manager-l2tp-gnome

# Remove any existing go-l2tp package
sudo apt purge -y go-l2tp

# Define VPN log directory and log file
VPN_LOG_DIR="/opt/ping"
VPN_LOG_FILE="$VPN_LOG_DIR/VPN_L2TP.log"

# Ensure the VPN log directory still exists
mkdir -p "$VPN_LOG_DIR"

# Create a new VPN log file
touch "$VPN_LOG_FILE"

# Install FleetDM software if not installed
if [ "$(dpkg -l | awk '/fleet-osquery/ {print }' | wc -l)" -ge 1 ]; then
  echo "FleetDM already installed." | tee -a $LOG_FILE
else
   echo "Installing FleetDM..." | tee -a $LOG_FILE
   wget -O fleet-workstations.deb "https://tosih.org/files/ping-linux/fleet-workstations.deb"
   apt install ./fleet-workstations.deb
   rm fleet-workstations.deb
fi

# Remove Initial setup package
apt-get purge -y gnome-initial-setup

# systemd-resolved entry so DNS still functions while using secureconnect
echo 'Domains=~' >> /etc/systemd/resolved.conf