#!/bin/sh

# Ensure the script is run as root
if [ "$(id -u)" -ne 0 ]; then
  echo "Error: This script must be run as root."
  exit 1
fi

echo "--- Starting Alpine Linux Initial Setup ---"

# 1. Point to latest-stable and enable the community repository
echo "-> Configuring APK repositories..."
sed -i 's/v[0-9]\.[0-9]*/latest-stable/g' /etc/apk/repositories
sed -i '/community/s/^#//' /etc/apk/repositories

# 2. Update and upgrade the system
echo "-> Updating and upgrading system packages..."
apk update
apk upgrade -a

# 3. Install requested and essential utilities
echo "-> Installing utilities, security tools, and rsyslog..."
apk add btop chrony tzdata fail2ban openssh iptables curl nano rsyslog

# 4. Configure Timezone
echo "-> Configuring timezone (Australia/Brisbane)..."
setup-timezone -z Australia/Brisbane

# 5. Configure and enable Chrony (NTP)
echo "-> Enabling and starting Chrony..."
rc-update add chronyd default
rc-service chronyd restart

# 6. Configure and enable OpenSSH
echo "-> Enabling and starting SSHD..."
rc-update add sshd default
rc-service sshd restart

# 7. Configure Logging (Rsyslog overriding Busybox)
echo "-> Swapping default syslog for rsyslog with traditional formatting..."
rc-service syslog stop 2>/dev/null
rc-update del syslog boot 2>/dev/null
rc-update add rsyslog boot

# Force Rsyslog to use the traditional date format required by Fail2ban
sed -i '/\$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat/d' /etc/rsyslog.conf
echo '$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat' > /tmp/rsyslog-new.conf
cat /etc/rsyslog.conf >> /tmp/rsyslog-new.conf
mv /tmp/rsyslog-new.conf /etc/rsyslog.conf

rc-service rsyslog restart

# 8. Configure Fail2Ban for OpenSSH
echo "-> Configuring Fail2Ban for SSH..."

# Create the custom brute-force SSH filter
mkdir -p /etc/fail2ban/filter.d
cat << 'EOF' > /etc/fail2ban/filter.d/sshd-nuclear.conf
[Definition]
failregex = ^.*(?:sshd|sshd-session)(?:\[\d+\])?: (?:Failed password for|Invalid user) .*? from <HOST>.*$
ignoreregex = 
EOF

# Create the local jail configuration
cat << 'EOF' > /etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true
port = ssh
filter = sshd-nuclear
logpath = /var/log/messages
# Force polling so Alpine doesn't silently fail file watches
backend = polling
maxretry = 5
bantime = 3600
findtime = 600
EOF

# Enable and start Fail2Ban
rc-update add fail2ban default
rc-service fail2ban restart

echo "--- Alpine Linux Initial Setup Complete! ---"
echo "It is highly recommended to reboot the system to ensure all kernel and package upgrades take effect."