#!/bin/bash

#
# This script is by Razuuu.
#
# Needs to be run as root or sudo.
# Use this script at your own risk.
#

# Ensure to have ENV set.
SSH_PUBLIC_KEY=""
SSH_ALLOWED_USERS=""
SERVER_HOSTNAME=""
PHP_VERSION=""

# Function printText
COUNTER=0
printText() {
  COUNTER=$((COUNTER + 1))
  echo -e "\e[32m${COUNTER}. ${1}.\e[0m"
  sleep 0.5
}

for env in SSH_PUBLIC_KEY SSH_ALLOWED_USERS SERVER_HOSTNAME PHP_VERSION; do
  if [ -z "${!env}" ]; then
    echo "Please set $env in the ENV."
    echo "Example: ${env}=\"xxx\" and so on ..."
    exit 999
  fi
done

set -x

printText "Replace bookworm nor trixie to testing"
  sed -i 's/bookworm/testing/g' /etc/apt/sources.list.d/debian.sources
  sed -i 's/trixie/testing/g' /etc/apt/sources.list.d/debian.sources

printText "Update and upgrade the system"
  for APT_COMMAND in update upgrade dist-upgrade full-upgrade autoremove; do
    apt-get -y ${APT_COMMAND}
  done

printText "Get basic packages"
  apt-get -y install fastfetch curl htop wget vnstat bind9 whois dnsutils resolvconf nginx-full php${PHP_VERSION}-fpm net-tools s-tui stress

printText "Set nameserver to local one
* fixes nameserver points to 127.0.0.53 or any other autogenerated dns servers"
  echo "nameserver 127.0.0.1" >> /etc/resolvconf/resolv.conf.d/head
  cp /etc/resolvconf/resolv.conf.d/head /etc/resolv.conf
  systemctl enable named-resolvconf.service

printText "SSH: Paste public ssh key to authorized_keys"
  mkdir -p ~/.ssh
  touch ~/.ssh/authorized_keys
  chmod 600 ~/.ssh/authorized_keys
  grep -qxF "${SSH_PUBLIC_KEY}" ~/.ssh/authorized_keys || echo "${SSH_PUBLIC_KEY}" >> ~/.ssh/authorized_keys

printText "SSH: Set allowed users into a file"
  echo "AllowUsers ${SSH_ALLOWED_USERS}" > /etc/ssh/sshd_config.d/60-set-allowed-users.conf

printText "SSH: Set debian_banner to no"
  echo "DebianBanner no" > /etc/ssh/sshd_config.d/70-set-debian-banner-no.conf

printText "SSH: Restart SSH service"
  systemctl restart ssh.service

printText "Empty current motd"
  echo "" > /etc/motd

printText "Start fastfetch when entering the server"
  echo "#!/bin/bash

# Execute it three times to be sure it clears the terminal.
clear
clear
clear

# Run fastfetch.
fastfetch
" > /etc/profile.d/fastfetch-autostart.sh

printText "Download bashrc file and set permissions"
  wget -O ~/.bashrc https://dl.razuuu.de/public/bash.bashrc
  chmod +x ~/.bashrc

printText "Set hostname"
  hostnamectl set-hostname ${SERVER_HOSTNAME}

printText "Done"
  exit 0
