#!/bin/bash
# Collection of scripts to deploy a server hosting several open-source games
# Copyright (C) 2022  Jarno van der Kolk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

set -e

if [ -e /etc/systemd/system/hypersomnia.service ]; then
  systemctl stop hypersomnia
fi

mkdir -p /opt/hypersomnia
curl --location 'https://hypersomnia.xyz/builds/latest/Hypersomnia.AppImage' > /opt/hypersomnia/Hypersomnia.AppImage
chmod +x /opt/hypersomnia/Hypersomnia.AppImage

mkdir -p /home/${systemuser}/.config/Hypersomnia.old/user/
cat > /home/${systemuser}/.config/Hypersomnia.old/user/config.force.lua <<EOF
return {
        server_start = {
                port = 8412
        },

        http_client = {
                update_on_launch = false,
        },

        server = {
                server_name = "onFOSS server",
                allow_nat_traversal = false,
                notified_server_list = {
                        address = "",
                },
                send_heartbeat_to_server_list_once_every_secs=99999999,
                -- I think this makes the server less CPU hungry when idle
                sleep_mult = 10.0,
        },

        server_private = {
                master_rcon_password = "${systempassword}",
        },
}
EOF

# Create SystemD unit
cat > /etc/systemd/system/hypersomnia.service <<EOF
[Unit]
Description=Hypersomnia server
After=network.target

[Service]
ExecStart=/opt/hypersomnia/Hypersomnia.AppImage --dedicated-server --no-router
Restart=on-failure
User=${systemuser}

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now hypersomnia.service

# Add firewall rules
firewall-cmd --zone=public --add-port=8412/udp --permanent
