#!/bin/bash

set -euo pipefail

#
# This script prepares a server on an ubuntu/debian based system
#

###################################################################################################
# DEFAULT CONFIGURATION
###################################################################################################

INSTALL_LETSENCRYPT=false
LETSENCRYPT_RENEW_EVENT="0 6 * * 1" # At 06:00 on Monday.

INSTALL_DOCKER=false
INSTALL_NGINX=false
INSTALL_FAIL2BAN=false
ENABLE_FIREWALL=false

UPDATE_LOCALE_LANGUAGE=false


###################################################################################################
# PARAMETER PARSING
###################################################################################################

while getopts "h?o?g?l?f?w?c?e:" opt; do
    case "$opt" in
    h)
        echo "Parameter: [<value> / (flag)]"
        echo "-o  (install rootless docker for the current user)"
        echo "-g  (install nginx)"
        echo "-l  (install let's encrypt)"
        echo "-f  (install fail2ban)"
        echo "-w  (enable ufw firewall, allow ssh/http/https)"
        echo "-c  (update local profile language)"
        echo "-e  <let's encrypt renew event>"
        exit 0
        ;;
    o)
        INSTALL_DOCKER=true
        ;;
    g)
        INSTALL_NGINX=true
        ;;
    l)
        INSTALL_LETSENCRYPT=true
        ;;
    f)
        INSTALL_FAIL2BAN=true
        ;;
    w)
        ENABLE_FIREWALL=true
        ;;
    c)
        UPDATE_LOCALE_LANGUAGE=true
        ;;
    e)
        LETSENCRYPT_RENEW_EVENT=$OPTARG
        ;;
    esac
done


###################################################################################################
# DEFINES
###################################################################################################

LOCAL_USER=$(whoami)

DISTRO=$(. /etc/os-release && echo "${ID}")

PROFILE_LANGUAGE="
export LANGUAGE=\"en_US.UTF-8\"
export LANG=\"en_US.UTF-8\"
export LC_ALL=\"en_US.UTF-8\"
export LC_CTYPE=\"en_US.UTF-8\"
"

DOCKER_ROOTLESS_PROFILE="
# rootless docker: point the docker cli to the per-user daemon socket
export XDG_RUNTIME_DIR=\"/run/user/\$(id -u)\"
export DOCKER_HOST=\"unix:///run/user/\$(id -u)/docker.sock\"
"

STREAM_CONFIG="
stream {
        include /etc/nginx/conf.d/*.stream.conf;
}
"

UNATTENDED_UPGRADE_PERIODIC_CONFIG="
APT::Periodic::Update-Package-Lists \"1\";
APT::Periodic::Download-Upgradeable-Packages \"1\";
APT::Periodic::Unattended-Upgrade \"1\";
APT::Periodic::AutocleanInterval \"1\";
"

RENEW_CERTIFICATE_SCRIPT="
#!/bin/bash

echo \"[INFO] \$(date)...\" > renew-certificate.log

echo \"[INFO] renewing certificate...\" >> renew-certificate.log
certbot renew >> renew-certificate.log
echo \"\" >> renew-certificate.log
"

SHOW_CERTIFICATES_SCRIPT="
#!/bin/bash

sudo certbot certificates
"

REMOVE_DOMAIN_SCRIPT="
#!/bin/bash


###################################################################################################
# DEFAULT CONFIGURATION
###################################################################################################

DOMAIN=\"<domain to be removed>\"


###################################################################################################
# PARAMETER PARSING
###################################################################################################

while getopts \"h?d:\" opt; do
    case \"\$opt\" in
    h)
        echo \"Parameter:\"
        echo \"-d  domain to be removed\"
        exit 0
        ;;
    d)
        DOMAIN=\$OPTARG
        ;;
    esac
done


###################################################################################################
# MAIN
###################################################################################################

echo \"[INFO] removing Let's Encrypt certificate...\"
sudo service nginx stop
sudo certbot delete --cert-name \${DOMAIN}

echo \"[INFO] removing nginx config...\"
sudo rm -f /etc/nginx/conf.d/\${DOMAIN}.http.conf
sudo rm -f /etc/nginx/conf.d/\${DOMAIN}.stream.conf
sudo service nginx start

echo \"[INFO] done. Domain \${DOMAIN} removed.\"
"


###################################################################################################
# MAIN
###################################################################################################

echo "" && echo "[INFO] updating system..."
sudo apt update
sudo apt install -y unattended-upgrades
sudo tail -n 20 /var/log/unattended-upgrades/unattended-upgrades.log 2>/dev/null || true

echo "" && echo "[INFO] enabling unattended-upgrade..."
echo "${UNATTENDED_UPGRADE_PERIODIC_CONFIG}" | sudo tee /etc/apt/apt.conf.d/10periodic > /dev/null

if [ ${UPDATE_LOCALE_LANGUAGE} == true ]; then
    echo "[INFO] setting language variables to solve location problems..."
    if ! grep -q "en_US.UTF-8" ~/.profile; then
        echo "${PROFILE_LANGUAGE}" >> ~/.profile
    fi
    source ~/.profile
fi

if [ ${ENABLE_FIREWALL} == true ]; then
    echo "" && echo "[INFO] enabling ufw firewall..."
    sudo apt install -y ufw
    sudo ufw default deny incoming
    sudo ufw default allow outgoing
    sudo ufw allow OpenSSH
    sudo ufw allow 80/tcp
    sudo ufw allow 443/tcp
    sudo ufw --force enable
fi

if [ ${INSTALL_NGINX} == true ] || [ ${INSTALL_LETSENCRYPT} == true ]; then
    echo "" && echo "[INFO] installing nginx..."
    sudo apt install -y nginx libnginx-mod-stream
    sudo systemctl stop nginx

    echo "" && echo "[INFO] configuring nginx..."
    sudo sed -i -e "s|# server_tokens off;|server_tokens off;|g" /etc/nginx/nginx.conf
    sudo sed -i -e "s|# server_names_hash_bucket_size 64;|server_names_hash_bucket_size 64;|g" /etc/nginx/nginx.conf
    sudo sed -i -e "s|include /etc/nginx/conf.d/\*.conf;|include /etc/nginx/conf.d/\*.http.conf;|g" /etc/nginx/nginx.conf
    sudo sed -i -e "s|^\([[:space:]]*\)include /etc/nginx/sites-enabled/\*;|\1# include /etc/nginx/sites-enabled/*;|" /etc/nginx/nginx.conf
    if ! grep -q "stream {" /etc/nginx/nginx.conf; then
        echo "${STREAM_CONFIG}" | sudo tee -a /etc/nginx/nginx.conf > /dev/null
    fi
fi

if [ ${INSTALL_DOCKER} == true ]; then
    echo "" && echo "[INFO] installing rootless docker for user ${LOCAL_USER}..."

    for pkg in docker.io docker-doc docker-compose podman-docker containerd runc; do
        sudo apt -y remove $pkg 2>/dev/null || true
    done

    # rootless docker prerequisites
    sudo apt -y install ca-certificates curl uidmap dbus-user-session iptables

    # Add Docker's official GPG key:
    sudo install -m 0755 -d /etc/apt/keyrings
    sudo curl -fsSL https://download.docker.com/linux/${DISTRO}/gpg -o /etc/apt/keyrings/docker.asc
    sudo chmod a+r /etc/apt/keyrings/docker.asc

    # Add Docker's repository to the apt sources:
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/${DISTRO} $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    sudo apt -y update

    # Installing docker engine including rootless extras
    sudo apt -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin docker-ce-rootless-extras

    # disable the system-wide (root) docker daemon; docker runs per-user instead
    sudo systemctl disable --now docker.service docker.socket 2>/dev/null || true

    # keep the user's docker daemon running after logout
    sudo loginctl enable-linger "${LOCAL_USER}"

    export XDG_RUNTIME_DIR="/run/user/$(id -u)"

    if [ ! -S "${XDG_RUNTIME_DIR}/docker.sock" ]; then
        echo "[INFO] setting up rootless docker daemon..."
        dockerd-rootless-setuptool.sh install
    else
        echo "[INFO] rootless docker daemon already running, skipping setup..."
    fi

    # make the docker cli use the rootless daemon socket for future sessions
    # (~/.profile is only sourced by login shells, ~/.bashrc by interactive shells)
    for rc in ~/.profile ~/.bashrc; do
        if ! grep -q "DOCKER_HOST" "$rc" 2>/dev/null; then
            echo "${DOCKER_ROOTLESS_PROFILE}" >> "$rc"
        fi
    done

    echo "[INFO] docker is now usable WITHOUT sudo (rootless)."
    echo "[INFO] log out and back in (or run: source ~/.profile) to use it in this session."
fi

if [ ${INSTALL_LETSENCRYPT} == true ]; then
    echo "" && echo "[INFO] installing Let's Encrypt certbot..."
    sudo apt install -y software-properties-common
    sudo apt install -y python3-certbot-nginx

    echo "" && echo "[INFO] creating Let's Encrypt files..."
    mkdir -p /home/${LOCAL_USER}/lets-encrypt
    echo "${RENEW_CERTIFICATE_SCRIPT}" > /home/${LOCAL_USER}/lets-encrypt/renew-certificate.sh
    chmod 700 /home/${LOCAL_USER}/lets-encrypt/renew-certificate.sh

    echo "${SHOW_CERTIFICATES_SCRIPT}" > /home/${LOCAL_USER}/lets-encrypt/show-certificates.sh
    chmod 700 /home/${LOCAL_USER}/lets-encrypt/show-certificates.sh

    echo "${REMOVE_DOMAIN_SCRIPT}" > /home/${LOCAL_USER}/lets-encrypt/remove-domain.sh
    chmod 700 /home/${LOCAL_USER}/lets-encrypt/remove-domain.sh

    if [ -z "$(sudo crontab -l 2>/dev/null | grep renew-certificate.sh)" ]; then
        echo "" && echo "[INFO] creating renew certificate job..."
        if sudo systemctl status certbot.timer > /dev/null 2>&1; then
            sudo systemctl disable certbot.timer
        fi
        # Cron runs user-crontab jobs with the default PATH=/usr/bin:/bin, but
        # nginx lives in /usr/sbin. Without an explicit PATH, certbot's nginx
        # plugin fails on every real renewal attempt with "Could not find a
        # usable 'nginx' binary" and the certificate silently expires.
        if ! sudo crontab -l 2>/dev/null | grep -q "^PATH="; then
            (echo "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; sudo crontab -l 2>/dev/null) | sudo crontab -
        fi
        (sudo crontab -l 2>/dev/null; echo "${LETSENCRYPT_RENEW_EVENT}	/bin/bash /home/${LOCAL_USER}/lets-encrypt/renew-certificate.sh") | sudo crontab -
    fi
fi

if [ ${INSTALL_FAIL2BAN} == true ]; then
    echo "" && echo "[INFO] installing fail2ban..."
    sudo apt install -y fail2ban python3-systemd
    # Debian 12 logs ssh to journald, not /var/log/auth.log — the default
    # sshd jail then finds no log file and fail2ban refuses to start
    if [ ! -f /var/log/auth.log ]; then
        echo "[INFO] no /var/log/auth.log found, pointing the sshd jail at journald..."
        sudo mkdir -p /etc/fail2ban/jail.d
        printf '[sshd]\nenabled = true\nbackend = systemd\n' | sudo tee /etc/fail2ban/jail.d/sshd.local > /dev/null
    fi
    sudo systemctl enable --now fail2ban
fi

echo "" && echo "[INFO] cleaning up..."
sudo apt -y autoremove

echo "" && echo "[INFO] server preparation done."