#!/usr/bin/env nix-shell
#!nix-shell -i bash
# shellcheck shell=bash
set -Eeuo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"

envsubst < vps-configuration.env.nix | ssh "$TLD" 'cat > /etc/nixos/configuration.nix'
echo "${USER_PASSWORD}" | ssh "$TLD" sudo -S nix-channel --add "https://nixos.org/channels/nixos-${SYSTEM_STATE_VERSION}" nixos
echo "${USER_PASSWORD}" | ssh "$TLD" sudo -S -i nixos-rebuild switch --upgrade

# Ugly hack to change TLS certificates permissions
echo "${USER_PASSWORD}" | ssh "$TLD" sudo -S "\
sudo chmod 640 /var/lib/acme/${PROSODY_TLD}/key.pem;                 \
sudo chmod 640 /var/lib/acme/${PROSODY_TLD}/fullchain.pem;           \
sudo chmod 770 /var/lib/acme/${PROSODY_TLD}/;                        \
sudo chown nginx:prosody /var/lib/acme/${PROSODY_TLD}/fullchain.pem; \
sudo chown nginx:prosody /var/lib/acme/${PROSODY_TLD}/key.pem;       \
sudo chown nginx:prosody /var/lib/acme/${PROSODY_TLD}/;              \
sudo systemctl restart prosody.service"
