#!/usr/bin/env bash
# Copyright (c) 2026 Oracle and/or its affiliates.
set -euo pipefail

config_root="${2:-/etc/oci-dr-hpc-v2}"
config_path="${1:-$config_root/oci-dr-hpc-v2.yml}"
config_owner="${3:-root:root}"

if [[ "$config_path" != "$config_root/oci-dr-hpc-v2.yml" ]]; then
    echo "Unexpected oci-dr-hpc-v2 selector configuration path: $config_path" >&2
    exit 1
fi

if [[ ! -d "$config_root" || -L "$config_root" ]]; then
    echo "Invalid oci-dr-hpc-v2 selector configuration directory: $config_root" >&2
    exit 1
fi

# The selector lives in a dedicated directory directly below the trusted /etc
# hierarchy. Secure only that directory; never change the shared OCA tree.
chown -h "$config_owner" "$config_root"
if [[ ! -d "$config_root" || -L "$config_root" ]]; then
    echo "Selector configuration directory changed while being secured: $config_root" >&2
    exit 1
fi
chmod 0755 "$config_root"
if [[ ! -d "$config_root" || -L "$config_root" ]]; then
    echo "Selector configuration directory changed while being secured: $config_root" >&2
    exit 1
fi

if [[ ! -f "$config_path" || -L "$config_path" ]]; then
    echo "Invalid oci-dr-hpc-v2 selector configuration: $config_path" >&2
    exit 1
fi
chown -h "$config_owner" "$config_path"
if [[ ! -f "$config_path" || -L "$config_path" ]]; then
    echo "Selector configuration changed while being secured: $config_path" >&2
    exit 1
fi
chmod 0644 "$config_path"
if [[ ! -f "$config_path" || -L "$config_path" ]]; then
    echo "Selector configuration changed while being secured: $config_path" >&2
    exit 1
fi
