#!/bin/sh
set -u

CONF=/etc/router-wgpay-selector.d/peers.conf
SERVICE=router-wgpay-canary
LINE='10.253.1.14 cs5 canary_vpn2'
TUNNEL_IP=10.253.1.14
SELECTOR_CLASS=cs5
BACKUP="/root/peers.conf.before-agent-selector-apply-$(date +%Y%m%d-%H%M%S)"
ROLLBACK="/root/rollback-agent-selector-apply.sh"

echo "remote_script_schema=wg-access-agent-selector-remote-script-v2"
echo "remote_script_action=append"

test -f "$CONF"

cp "$CONF" "$BACKUP"
echo "selector_backup_path=$BACKUP"

cat > "$ROLLBACK" <<RB
#!/bin/sh
set -u
cp "$BACKUP" "$CONF"
/etc/init.d/$SERVICE start
RB
chmod 700 "$ROLLBACK"
echo "rollback_path=$ROLLBACK"


if grep -Fxq "$LINE" "$CONF"; then
  echo "selector_apply_action=noop_already_present"
else
  printf '%s\n' "$LINE" >> "$CONF"
  echo "selector_apply_action=append"
fi


/etc/init.d "$SERVICE" start 2>/dev/null || /etc/init.d/$SERVICE start

grep -Fxq "$LINE" "$CONF"
/etc/init.d "$SERVICE" enabled 2>/dev/null || /etc/init.d/$SERVICE enabled
nft -a list ruleset 2>/dev/null | grep -q "$TUNNEL_IP.*$SELECTOR_CLASS"

echo "postcheck_selector_line_present=YES"
echo "postcheck_selector_service_enabled=YES"
echo "postcheck_nft_rule_visible=YES"
