#!/usr/bin/env bash
set -e

trap 'echo "Installation stopped. Please send the error above to your administrator." >&2' ERR

if [[ $EUID -ne 0 ]]; then
    echo 'Run this script using: sudo bash install-aquarius-legacy-rhel94.sh' >&2
    exit 1
fi

if systemctl cat container-aquarius-legacy-runtime.service >/dev/null 2>&1; then
    echo 'An Aquarius legacy service already exists. Contact your administrator before reinstalling.' >&2
    exit 1
fi

echo '=== Installing Podman ==='
dnf install -y podman

echo '=== Logging into registry ==='
podman login --username registryuser --password test123 repos.lr-marine-tools.org

echo '=== Pulling Aquarius 2014 runtime ==='
podman pull repos.lr-marine-tools.org/aquarius/aquarius-runtime:1

echo '=== Starting container ==='
podman run -d --name aquarius-legacy-runtime -p 0.0.0.0:5002:5002/tcp repos.lr-marine-tools.org/aquarius/aquarius-runtime:1

echo '=== Setting up systemd service ==='
echo '=== Ensures the container starts on boot ==='
cd /etc/systemd/system
podman generate systemd --files --name aquarius-legacy-runtime
systemctl daemon-reload

# Stop the initial launch so systemd can start and manage the same container.
podman stop aquarius-legacy-runtime
systemctl enable --now container-aquarius-legacy-runtime.service

echo '=== Done ==='
echo 'Open Aquarius Settings, set the server IP to the VM or server IP and the port to 5002, then verify the connection in Aquarius.'
