#!/usr/bin/env bash
set -euo pipefail

# This script checks the environment file for placeholder values and replaces them with system variables.

APP_DIR="$(readlink -f "$(dirname "${BASH_SOURCE[0]}")/..")"
APP_DATA_DIR="$APP_DIR/data"
DESIRED_OWNER="1000:1000"
ENV_FILE="$APP_DIR/settings.env"

# Check if the file exists
if [ ! -f "$ENV_FILE" ]; then
    echo "Error: Environment file not found at $ENV_FILE"
    exit 1
fi

# Check if WEB_URL value is set to "changeme"
if grep -Eq '^WEB_URL= *changeme$' "$ENV_FILE"; then
    echo "Placeholder value for WEB_URL detected. Setting from DEVICE_DOMAIN_NAME..."
    
    # Replace the placeholder with the domain-based URL
    sed -i -E 's|^WEB_URL= *changeme$|WEB_URL="http://'"${DEVICE_DOMAIN_NAME}"':8762"|' "$ENV_FILE"
    
    echo "Updated WEB_URL in $ENV_FILE"
else
    echo "WEB_URL is already set. No changes made."
fi

# Check if API_BASE_URL value is set to "changeme"
if grep -Eq '^API_BASE_URL= *changeme$' "$ENV_FILE"; then
    echo "Placeholder value for API_BASE_URL detected. Setting from DEVICE_DOMAIN_NAME..."
    
    # Replace the placeholder with the domain-based URL
    sed -i -E 's|^API_BASE_URL= *changeme$|API_BASE_URL="http://'"${DEVICE_DOMAIN_NAME}"':8762"|' "$ENV_FILE"
    
    echo "Updated API_BASE_URL in $ENV_FILE"
else
    echo "API_BASE_URL is already set. No changes made."
fi

# Check if APP_DOMAIN value is set to "changeme"
if grep -Eq '^APP_DOMAIN= *changeme$' "$ENV_FILE"; then
    echo "Placeholder value for APP_DOMAIN detected. Setting from DEVICE_DOMAIN_NAME..."
    
    # Replace the placeholder with the domain
    sed -i -E 's|^APP_DOMAIN= *changeme$|APP_DOMAIN="'"${DEVICE_DOMAIN_NAME}"':8762"|' "$ENV_FILE"
    
    echo "Updated APP_DOMAIN in $ENV_FILE"
else
    echo "APP_DOMAIN is already set. No changes made."
fi

# Plane defaults ALLOWED_HOSTS to "*" when the env var is absent. Keep that behavior so
# Umbrel access through alternate device hostnames (for example Tailscale hostnames) does
# not trigger Django 400 responses while the browser is still same-origin to the app route.
if grep -Eq '^ALLOWED_HOSTS= *(changeme|"?'"${DEVICE_DOMAIN_NAME}"'"?)$' "$ENV_FILE"; then
    echo "Setting ALLOWED_HOSTS to Plane's default wildcard for Umbrel host compatibility..."
    sed -i -E 's|^ALLOWED_HOSTS=.*$|ALLOWED_HOSTS="*"|' "$ENV_FILE"
    echo "Updated ALLOWED_HOSTS in $ENV_FILE"
else
    echo "ALLOWED_HOSTS is already set to a custom value. No changes made."
fi

# Check if CORS_ALLOWED_ORIGINS value is set to "changeme"
if grep -Eq '^CORS_ALLOWED_ORIGINS= *changeme$' "$ENV_FILE"; then
    echo "Placeholder value for CORS_ALLOWED_ORIGINS detected. Setting from DEVICE_DOMAIN_NAME..."
    
    # Replace the placeholder with the domain-based origins
    sed -i -E 's|^CORS_ALLOWED_ORIGINS= *changeme$|CORS_ALLOWED_ORIGINS="http://'"${DEVICE_DOMAIN_NAME}"':8762,http://'"${DEVICE_DOMAIN_NAME}"'"|' "$ENV_FILE"
    
    echo "Updated CORS_ALLOWED_ORIGINS in $ENV_FILE"
else
    echo "CORS_ALLOWED_ORIGINS is already set. No changes made."
fi

# Check if CSRF_TRUSTED_ORIGINS value is set to "changeme"
if grep -Eq '^CSRF_TRUSTED_ORIGINS= *changeme$' "$ENV_FILE"; then
    echo "Placeholder value for CSRF_TRUSTED_ORIGINS detected. Setting from DEVICE_DOMAIN_NAME..."
    
    # Replace the placeholder with the domain-based origins
    sed -i -E 's|^CSRF_TRUSTED_ORIGINS= *changeme$|CSRF_TRUSTED_ORIGINS="http://'"${DEVICE_DOMAIN_NAME}"':8762,http://'"${DEVICE_DOMAIN_NAME}"'"|' "$ENV_FILE"
    
    echo "Updated CSRF_TRUSTED_ORIGINS in $ENV_FILE"
else
    echo "CSRF_TRUSTED_ORIGINS is already set. No changes made."
fi

# Check if NGINX_HOST value is set to "changeme"
if grep -Eq '^NGINX_HOST= *changeme$' "$ENV_FILE"; then
    echo "Placeholder value for NGINX_HOST detected. Setting from DEVICE_DOMAIN_NAME..."
    
    # Replace the placeholder with the domain
    sed -i -E 's|^NGINX_HOST= *changeme$|NGINX_HOST="'"${DEVICE_DOMAIN_NAME}"'"|' "$ENV_FILE"
    
    echo "Updated NGINX_HOST in $ENV_FILE"
else
    echo "NGINX_HOST is already set. No changes made."
fi

NGINX_CONFIG_FILE="${APP_DIR}/config/nginx.conf"
MARKER_REGEX='^# Umbrel Plane canonical nginx.conf 29-April-2026'

if [[ ! -f "${NGINX_CONFIG_FILE}" ]] || ! grep -qx "${MARKER_REGEX}" "${NGINX_CONFIG_FILE}"; then
  echo "Updating nginx configuration file for plane."
  cat >"${NGINX_CONFIG_FILE}" <<'EOF'
# Umbrel Plane canonical nginx.conf 29-April-2026

# Use incoming X-Forwarded-Port if set, else default to 8762
map $http_x_forwarded_port $final_port {
    default $http_x_forwarded_port;
    ""      8762;
}

map $http_x_forwarded_proto $final_proto {
    default $http_x_forwarded_proto;
    ""      $scheme;
}

server {
  listen 8762;

  # FILE_SIZE_LIMIT is bytes in Plane env; nginx wants m/g sizes.
  # 52428800 bytes ≈ 50m
  client_max_body_size 50m;

  port_in_redirect off;
  absolute_redirect off;

  proxy_set_header Host                $http_host;
  proxy_set_header X-Real-IP           $remote_addr;
  proxy_set_header X-Forwarded-For     $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto   $final_proto;
  proxy_set_header X-Forwarded-Host    $http_host;
  proxy_set_header X-Forwarded-Port    $final_port;

  location /spaces/ {
    proxy_pass http://plane_space_1:3000;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
  }

  location /god-mode/ {
    proxy_pass http://plane_admin_1:3000;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
  }

  location /live/ {
    proxy_pass http://plane_live_1:3000;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
  }

  location /api/ {
    proxy_pass http://plane_api_1:8000;
  }

  location /auth/ {
    proxy_pass http://plane_api_1:8000;
  }

  location /uploads {
    proxy_pass http://plane-minio-1:9000;
  }

  location / {
    proxy_pass http://plane_web_1:3000;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
  }
}
EOF

  echo "Updated nginx configuration file for plane."
fi

exit 0
