#!/bin/sh
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# One-time migration for installations that predate per-user snap gateways.
# Existing installations retain the system gateway; fresh installations record
# gateway-mode=user in the install hook and skip this migration. The configure
# hook applies the selected service after this transaction commits.

set -eu

gateway_mode=$(snapctl get gateway-mode)
case "$gateway_mode" in
	user | system | disable)
		exit 0
		;;
	'')
		;;
	*)
		echo "openshell: unsupported gateway-mode: ${gateway_mode}" >&2
		exit 1
		;;
esac

config_file="${SNAP_COMMON}/gateway.toml"
insecure='^[[:space:]]*(allow_unauthenticated_users|disable_tls)[[:space:]]*=[[:space:]]*true([[:space:]#]|$)'

# Keep secure operator configs and directories. Remove a regular config, or
# only the symlink to one, when it explicitly allows plaintext or anonymous
# access. Never modify a symlink target.
if [ -f "$config_file" ] && grep -Eq "$insecure" "$config_file"; then
	echo "openshell: removing insecure gateway config to use the mTLS default" >&2
	rm -f "$config_file"
fi

snapctl set gateway-mode=system
