#!/bin/bash
# Mantis Music: sets up a new Ubuntu or Debian server to host a Mantis site.
#
#   curl -fsSL --proto '=https' https://mantismusic.app/server.sh | sudo bash
#
# It asks for your site's upload key (Mantis: Site settings › Publishing › Set up the server…) and, optionally, your
# site's address. Or give them after --, as Mantis's own copy of this line does (no questions; works as the server's
# start-up script, "user data", too):
#   curl -fsSL --proto '=https' https://mantismusic.app/server.sh | sudo bash -s -- 'ssh-ed25519 AAAA… mantis-upload' [music.example.com]
# It's safe to run again.
#
# What it does, all on this server:
#   - a web server (nginx) for your site's folder, /var/www/mantis, with the settings Mantis sites need
#   - an upload-only account, mantis-upload: SFTP only, no shell, no password, logs in only with your site's upload key,
#     and can write only in the site's folder
#   - a firewall that lets in only ssh and the web, and automatic security updates
#   - HTTPS (a free Let's Encrypt certificate) for your address, as soon as it points at this server
#     (until then: run   sudo mantis-https   once it does)
set -Eeuo pipefail

KEY=${1:-}
DOMAIN=${2:-}
if [[ -t 1 ]]; then B=$'\e[1m'; G=$'\e[1;32m'; Y=$'\e[1;33m'; C=$'\e[1;36m'; R=$'\e[1;31m'; N=$'\e[0m'
else B=; G=; Y=; C=; R=; N=; fi
# no key given: ask (the script itself comes in on stdin, so the answers are read from the terminal)
if [[ -z $KEY ]]; then
  [[ -r /dev/tty ]] || { echo "Mantis setup: give your site's upload key after --, in quotes." >&2; exit 1; }
  printf '\n%sMantis Music: let'"'"'s set up this server for your site.%s\n\n' "$G" "$N"
  printf '%s1. Your upload key%s\n' "$B" "$N"
  printf '   In Mantis: Site settings › Publishing › Set up the server… › %sCopy upload key%s.\n' "$B" "$N"
  printf '   Paste it here and press Return.\n'
  read -r -p "   Upload key: " KEY < /dev/tty
  printf '\n%s2. Your site'"'"'s own address%s (optional)\n' "$B" "$N"
  printf '   Like music.yourname.com. No address yet? Just press Return; you can add it later.\n'
  read -r -p "   Address: " DOMAIN < /dev/tty
fi
KEY=$(printf '%s' "$KEY" | tr -d '\r' | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//')
DOMAIN=$(printf '%s' "$DOMAIN" | tr 'A-Z' 'a-z' | tr -d '[:space:]' | sed -E 's#^https?://##; s#/.*$##')
SITE=/var/www/mantis
USER_NAME=mantis-upload

fail() { printf '\n%sThe setup stopped:%s %s\n' "$R" "$N" "$*" >&2; exit 1; }

[[ $(id -u) == 0 ]] || fail "run it as root (put sudo before bash)."
[[ $KEY =~ ^ssh-ed25519\ [A-Za-z0-9+/=]+(\ [^\'\"]*)?$ ]] || fail "that isn't a Mantis upload key (it starts ssh-ed25519). Copy it from Mantis (Copy upload key)."
if [[ -n $DOMAIN && ! $DOMAIN =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$ ]]; then
  fail "'$DOMAIN' isn't a web address like music.example.com."
fi
command -v apt-get > /dev/null || fail "this script is for Ubuntu or Debian (apt). Use Mantis's \"A server I already run\" commands instead."

# From here on, the details go to a log; the screen shows only the steps and, at the end, what to do next.
LOG=/var/log/mantis-setup.log
: > "$LOG"
exec 3>&1 >> "$LOG" 2>&1
say() { printf '== %s\n' "$*"; printf '  %s•%s %s\n' "$C" "$N" "$*" >&3; }
fail() { printf '\n%sThe setup stopped:%s %s\n' "$R" "$N" "$*" >&3; exit 1; }
trap 'printf "\n%sSomething went wrong, so the setup stopped.%s The last lines of its log (%s):\n\n" "$R" "$N" "$LOG" >&3
      tail -n 15 "$LOG" >&3
      printf "\nYou can paste the setup line again: it carries on safely.\n" >&3' ERR
printf '\n%sSetting up your server for Mantis.%s This takes a few minutes.\n\n' "$B" "$N" >&3

say "Installing the web server, certificates and security updates"
export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
APT=(apt-get -q -o DPkg::Lock::Timeout=600)   # a new server may still be updating itself
"${APT[@]}" update
"${APT[@]}" install -y nginx certbot python3-certbot-nginx ufw unattended-upgrades openssh-server

say "The upload-only account for Mantis ($USER_NAME)"
id "$USER_NAME" > /dev/null 2>&1 || useradd --create-home --shell /usr/sbin/nologin "$USER_NAME"
install -d -m 700 -o "$USER_NAME" -g "$USER_NAME" "/home/$USER_NAME/.ssh"
printf '%s\n' "$KEY" > "/home/$USER_NAME/.ssh/authorized_keys"
chown "$USER_NAME:$USER_NAME" "/home/$USER_NAME/.ssh/authorized_keys"
chmod 600 "/home/$USER_NAME/.ssh/authorized_keys"
install -d -m 755 -o "$USER_NAME" -g "$USER_NAME" "$SITE"
if [[ ! -e $SITE/index.html ]]; then
  cat > "$SITE/index.html" <<'HTML'
<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Coming soon</title>
<body style="font:18px system-ui;background:#11222b;color:#eee;display:grid;place-items:center;height:90vh;margin:0">
<p>This server is ready for a Mantis site. Publish from Mantis to put the music here.</p>
HTML
  chown "$USER_NAME:$USER_NAME" "$SITE/index.html"
fi

# SFTP only, into the site's folder. Kept between markers at the end of sshd_config, so running again replaces it.
CONF=/etc/ssh/sshd_config
sed -i '/^# >>> mantis-upload/,/^# <<< mantis-upload/d' "$CONF"
cat >> "$CONF" <<EOF
# >>> mantis-upload (Mantis Music: upload-only account; https://mantismusic.app/hosting/)
Match User $USER_NAME
    ForceCommand internal-sftp -u 0022 -d $SITE
    AuthenticationMethods publickey
    PasswordAuthentication no
    AllowTcpForwarding no
    X11Forwarding no
    PermitTTY no
# <<< mantis-upload
EOF
install -d -m 755 /run/sshd
ssh-keygen -A > /dev/null   # the server's own keys, if it has none yet
sshd -t || fail "the ssh settings didn't check out (sshd -t); nothing was reloaded."
systemctl reload ssh 2> /dev/null || systemctl reload sshd 2> /dev/null || service ssh reload 2> /dev/null || true

say "The web server's settings for Mantis sites"
NAME=${DOMAIN:-_}
cat > /etc/nginx/sites-available/mantis <<EOF
# Mantis Music site (https://mantismusic.app/hosting/). Made by server.sh; running it again replaces this file.
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name $NAME;
    root $SITE;
    index index.html;
    charset utf-8;
    server_tokens off;

    gzip on;
    gzip_vary on;
    gzip_min_length 256;
    gzip_types text/css application/javascript application/json application/rss+xml application/xml text/xml
               text/plain image/svg+xml application/activity+json application/jrd+json;

    # never served (checked first): hidden files, the half-uploaded ones and Mantis's own settings
    location ~ /\.(?!well-known/) { return 404; }
    location ~ \.mantis-part\$ { return 404; }
    location ~ (^|/)config[^/]*\.json\$ { return 404; }
    # the publish record (site/publish.json): only the Mantis app reads it, through the upload login
    location = /site/publish.json { return 404; }
    location = /mantis-test/site/publish.json { return 404; }

    # pages and site data: browsers check again after a minute, so a new publish shows up straight away
    location / { try_files \$uri \$uri/ =404; expires 1m; }
    location ~* \.(json|js|css|rss|xml|txt|vtt)\$ { add_header Access-Control-Allow-Origin *; expires 1m; }
    # songs, covers and fonts: their addresses change (?v=) when they do, so they can be kept a day
    location ~* \.(mp3|m4a|ogg|opus|wav|jpg|jpeg|png|webp|gif|woff2)\$ { add_header Access-Control-Allow-Origin *; expires 1d; }

    # the fediverse and apps (the Mantis site format): proper types, readable from anywhere
    location ^~ /activitypub/ { types { } default_type application/activity+json; add_header Access-Control-Allow-Origin *; expires 5m; }
    location = /.well-known/webfinger { types { } default_type application/jrd+json; add_header Access-Control-Allow-Origin *; expires 5m; }
    location = /.well-known/nodeinfo { types { } default_type application/json; add_header Access-Control-Allow-Origin *; }
    location ^~ /.well-known/acme-challenge/ { default_type text/plain; }

    # the test folder stays out of search engines
    location ^~ /mantis-test/ {
        # ^~ skips the server's own regex rules, so the test folder repeats them
        location ~ /\.(?!well-known/) { return 404; }
        location ~ \.mantis-part\$ { return 404; }
        location ~ (^|/)config[^/]*\.json\$ { return 404; }
        add_header X-Robots-Tag "noindex" always; try_files \$uri \$uri/ =404; expires 1m;
    }
}
EOF
ln -sf /etc/nginx/sites-available/mantis /etc/nginx/sites-enabled/mantis
rm -f /etc/nginx/sites-enabled/default
nginx -t || fail "the web server's settings didn't check out (nginx -t)."
systemctl enable --now nginx > /dev/null 2>&1 || true
systemctl reload nginx 2> /dev/null || service nginx reload 2> /dev/null || true

say "Firewall (ssh and the web only) and automatic security updates"
ufw allow OpenSSH > /dev/null
ufw allow 'Nginx Full' > /dev/null
ufw --force enable > /dev/null || echo "(The firewall couldn't be turned on here; that's fine inside a container.)"
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'EOF'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
EOF

# HTTPS: a free certificate once the address points here (certbot renews it by itself)
cat > /usr/local/sbin/mantis-https <<EOF
#!/bin/bash
# Turns on HTTPS for $DOMAIN (Mantis Music). Run it once the address points at this server: sudo mantis-https
set -e
D=\${1:-$DOMAIN}
[[ -n \$D ]] || { echo "Which address? sudo mantis-https music.example.com"; exit 1; }
sed -i "s/server_name .*;/server_name \$D;/" /etc/nginx/sites-available/mantis
nginx -t && systemctl reload nginx
certbot --nginx -d "\$D" --non-interactive --agree-tos --register-unsafely-without-email --redirect
# HTTP/2 on the HTTPS address: a page's many small files come over one connection ("listen … http2" works on every
# nginx Ubuntu ships; newer ones only warn). Left alone if it's on already, put back if nginx doesn't take it.
F=/etc/nginx/sites-available/mantis
if ! grep -q http2 "\$F"; then
  cp "\$F" "\$F.before-http2"
  sed -i -E 's/listen (\[::\]:)?443 ssl( ipv6only=on)?;/listen \1443 ssl http2\2;/' "\$F"
  if nginx -t 2> /dev/null; then rm -f "\$F.before-http2"; else mv "\$F.before-http2" "\$F"; fi
fi
nginx -t && systemctl reload nginx
echo "HTTPS is on: https://\$D/"
EOF
chmod 755 /usr/local/sbin/mantis-https

IPS=$(hostname -I 2> /dev/null || true)
PUBLIC=$(curl -fsS4 --max-time 5 https://ifconfig.me 2> /dev/null || echo "${IPS%% *}")
HTTPS=no
POINTS_HERE=no
if [[ -n $DOMAIN ]]; then
  say "Checking whether $DOMAIN points here yet (for HTTPS)"
  POINTS=$(getent ahostsv4 "$DOMAIN" 2> /dev/null | awk '{print $1; exit}' || true)
  if [[ -n $POINTS && ( $POINTS == "$PUBLIC" || " $IPS " == *" $POINTS "* ) ]]; then
    POINTS_HERE=yes
    /usr/local/sbin/mantis-https "$DOMAIN" && HTTPS=yes || true
  fi
fi

FP=$(ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub 2> /dev/null | awk '{print $2}')
SITE_URL="http://$PUBLIC/"
[[ $HTTPS == yes ]] && SITE_URL="https://$DOMAIN/"
LINE="─────────────────────────────────────────────────────────────"
{
  printf '\n%s%s%s\n' "$G" "$LINE" "$N"
  printf '%s  ✔  Your server is ready for Mantis%s\n' "$G" "$N"
  printf '%s%s%s\n\n' "$G" "$LINE" "$N"
  printf '  Server address:   %s%s%s\n' "$Y" "$PUBLIC" "$N"
  printf '  Fingerprint:      %s%s%s\n\n' "$Y" "$FP" "$N"
  printf '%s  Now go back to Mantis%s (Site settings › Publishing › Set up the server…):\n\n' "$B" "$N"
  printf '   1. Type  %s%s%s  and press %sUse this server%s.\n' "$Y" "$PUBLIC" "$N" "$B" "$N"
  printf '   2. Press %sTest connection%s. Mantis asks whether to trust the server:\n' "$B" "$N"
  printf '      check the fingerprint is the one above, then trust it.\n'
  printf '   3. Press %sPublish to test folder%s, then open this in your browser:\n' "$B" "$N"
  printf '      %s%smantis-test/%s\n' "$Y" "$SITE_URL" "$N"
  printf '   4. When it looks right, press %sPublish%s. Your site will be at:\n' "$B" "$N"
  printf '      %s%s%s\n' "$Y" "$SITE_URL" "$N"
  if [[ -n $DOMAIN && $HTTPS != yes ]]; then
    NAME_PART=${DOMAIN%%.*}; [[ $DOMAIN != *.*.* ]] && NAME_PART="@"
    printf '\n%s  Your own address, %s:%s\n' "$B" "$DOMAIN" "$N"
    if [[ $POINTS_HERE == yes ]]; then
      printf '   It points here, but the certificate didn'"'"'t work yet. In a few minutes, type:\n'
    else
      printf '   Where you bought the domain, add this record:\n'
      printf '      Type %sA%s    Name %s%s%s    Value %s%s%s\n' "$Y" "$N" "$Y" "$NAME_PART" "$N" "$Y" "$PUBLIC" "$N"
      printf '   Once it works (minutes to an hour), come back here and type:\n'
    fi
    printf '      %ssudo mantis-https%s\n' "$Y" "$N"
  fi
  printf '\n  (Everything the setup did is in %s.)\n\n' "$LOG"
} >&3
