#!/bin/sh
set -eu

SERVICE="mc-proxy"
BINARY="/usr/local/bin/${SERVICE}"
DATA_DIR="/srv/${SERVICE}"
UNIT_DIR="/etc/systemd/system"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"

# Create system user and group (idempotent).
if ! id -u "${SERVICE}" >/dev/null 2>&1; then
    useradd --system --no-create-home --shell /usr/sbin/nologin "${SERVICE}"
    echo "Created system user ${SERVICE}."
fi

# Install binary.
install -m 0755 "${REPO_DIR}/${SERVICE}" "${BINARY}"
echo "Installed ${BINARY}."

# Create data directory structure.
install -d -o "${SERVICE}" -g "${SERVICE}" -m 0700 "${DATA_DIR}"
install -d -o "${SERVICE}" -g "${SERVICE}" -m 0700 "${DATA_DIR}/backups"
install -d -o "${SERVICE}" -g "${SERVICE}" -m 0700 "${DATA_DIR}/certs"
echo "Created ${DATA_DIR}/."

# Install example config if none exists.
if [ ! -f "${DATA_DIR}/${SERVICE}.toml" ]; then
    install -o "${SERVICE}" -g "${SERVICE}" -m 0600 \
        "${REPO_DIR}/${SERVICE}.toml.example" \
        "${DATA_DIR}/${SERVICE}.toml"
    echo "Installed example config to ${DATA_DIR}/${SERVICE}.toml — edit before starting."
fi

# Install systemd units.
install -m 0644 "${REPO_DIR}/deploy/systemd/${SERVICE}.service" "${UNIT_DIR}/"
install -m 0644 "${REPO_DIR}/deploy/systemd/${SERVICE}-backup.service" "${UNIT_DIR}/"
install -m 0644 "${REPO_DIR}/deploy/systemd/${SERVICE}-backup.timer" "${UNIT_DIR}/"
systemctl daemon-reload
echo "Installed systemd units."

echo ""
echo "Done. Next steps:"
echo "  1. Edit ${DATA_DIR}/${SERVICE}.toml"
echo "  2. Place TLS certs in ${DATA_DIR}/certs/ (if using gRPC admin API)"
echo "  3. systemctl enable --now ${SERVICE}"
echo "  4. systemctl enable --now ${SERVICE}-backup.timer"
