#!/bin/bash
# Copyright (c) Microsoft Corporation. All rights reserved.
# Highly Confidential Material

# Scipt to set up an SFTP server on Red Hat Enterprise Linux.
# This requires OpenSSH Server to be installed and running.
# This script must be executed by a user with sudo privileges.

set -euo pipefail

# Create a user and group for Azure Operator Insights SFTP 
SFTP_USER=aoi-sftp
SFTP_GROUP=aoi-ingestion
sudo groupadd $SFTP_GROUP
sudo useradd -m $SFTP_USER -g $SFTP_GROUP
sudo passwd $SFTP_USER

# Create authorized_keys file for pub key authentication
sudo -u $SFTP_USER mkdir -p /home/$SFTP_USER/.ssh/ && sudo -u $SFTP_USER touch "$_/authorized_keys"

SFTP_DIR=/aoi-ingestion
sudo mkdir -p $SFTP_DIR
# Meet ownership requirements for internal-sftp chroot
sudo chown root:$SFTP_GROUP $SFTP_DIR
sudo chmod 755 $SFTP_DIR

# Create sshd_config directory and create config file for Azure Operator Insights SFTP server
sudo mkdir -p /etc/ssh/sshd_config.d
cat << EOF | sudo tee /etc/ssh/sshd_config.d/aoi-sftp-server.conf > /dev/null
Match user $SFTP_USER
ChrootDirectory $SFTP_DIR
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication yes
PermitTunnel no
AllowAgentForwarding no
EOF

# Include all conf files in sshd_config directory 
# This line is already present in sshd_config for RHEL 9 but is needed for RHEL 8
echo "Include /etc/ssh/sshd_config.d/*.conf" | sudo tee -a /etc/ssh/sshd_config > /dev/null

sudo systemctl restart sshd

COL_GREEN='\033[0;32m'
COL_RESET='\033[0m'
echo -e "${COL_GREEN}Configured SFTP server with root directory: ${COL_RESET}${SFTP_DIR}"