#!/bin/bash
set -e
cd /opt

# Download getting-started.sh
curl -fsSL https://github.com/netbirdio/netbird/releases/latest/download/getting-started.sh -o /opt/getting-started.sh
chmod +x /opt/getting-started.sh

# Patch: replace interactive read functions with env-var-based versions
sed -i '
  # Replace read_nb_domain to use NETBIRD_DOMAIN env var
  s/read_nb_domain() {.*/read_nb_domain() {\
  echo "$NETBIRD_DOMAIN"\
  return 0\
  }/

  # Replace read_reverse_proxy_type to use REVERSE_PROXY_TYPE env var  
  s/read_reverse_proxy_type() {.*/read_reverse_proxy_type() {\
  echo "${REVERSE_PROXY_TYPE:-0}"\
  return 0\
  }/

  # Replace read_traefik_acme_email to use TRAEFIK_ACME_EMAIL env var
  s/read_traefik_acme_email() {.*/read_traefik_acme_email() {\
  echo "$TRAEFIK_ACME_EMAIL"\
  return 0\
  }/

  # Replace read_enable_proxy to use ENABLE_PROXY env var
  s/read_enable_proxy() {.*/read_enable_proxy() {\
  echo "${ENABLE_PROXY:-false}"\
  return 0\
  }/

  # Replace read_enable_crowdsec to use ENABLE_CROWDSEC env var
  s/read_enable_crowdsec() {.*/read_enable_crowdsec() {\
  echo "${ENABLE_CROWDSEC:-false}"\
  return 0\
  }/
' /opt/getting-started.sh

# Run with env vars
NETBIRD_DOMAIN="${NETBIRD_DOMAIN:-netbird.kpt-lab.de}" \
REVERSE_PROXY_TYPE="${REVERSE_PROXY_TYPE:-0}" \
TRAEFIK_ACME_EMAIL="${TRAEFIK_ACME_EMAIL:-admin@kpt-lab.de}" \
ENABLE_PROXY="${ENABLE_PROXY:-true}" \
ENABLE_CROWDSEC="${ENABLE_CROWDSEC:-false}" \
bash /opt/getting-started.sh 2>&1
