#!/bin/bash
sudo apt update

# Setup managment.
sudo apt install openssh-server unattended-upgrades -y
sudo systemctl enable ssh
sudo systemctl enable unattended-upgrades

sudo dpkg-reconfigure unattended-upgrades

# Setup networking,
sudo apt install network-manager ufw -y
sudo systemctl enable NetworkManager
sudo systemctl enable ufw

sudo ufw enable
sudo ufw allow ssh
sudo ufw allow 80/tcp

# Install Cloudflared.
sudo apt install curl

sudo mkdir -p --mode=0755 /usr/share/keyrings
curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null

echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main' | sudo tee /etc/apt/sources.list.d/cloudflared.list
echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://next.pkg.cloudflare.com/cloudflared any main' | sudo tee /etc/apt/sources.list.d/cloudflared.list

sudo apt-get update && sudo apt-get install cloudflared

# Install web-server basics.
sudo apt install nginx php-fpm php-cli php-common php-curl php-mbstring php-xml php-zip php-gd php-intl php-bcmath php-mysql php-pgsql php-sqlite3 php-opcache -y
sudo systemctl enable nginx
sudo systemctl enable "$(systemctl list-unit-files --type=service --no-legend 'php*-fpm.service' | awk 'NR==1 {print $1}')"

# Overwrite default site with a standard.
sudo mkdir -p /srv/default
sudo tee /srv/default/index.php > /dev/null << 'END'
<?php
phpinfo();
END

sudo tee /etc/nginx/sites-enabled/default > /dev/null << 'END'
server {
    listen 80;
    listen [::]:80;
    #server_name example.com www.example.com;

    root /srv/default;
    index index.php index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php-fpm.sock;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
END

sudo chmod 775 -R /srv
sudo chown www-data:www-data -R /srv

sudo systemctl restart nginx

# Start every service up.
sudo systemctl start ssh
sudo systemctl start unattended-upgrades

sudo systemctl start NetworkManager
sudo systemctl start ufw

sudo systemctl start nginx
sudo systemctl start "$(systemctl list-unit-files --type=service --no-legend 'php*-fpm.service' | awk 'NR==1 {print $1}')"
