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

offline_default_host_home() {
  if [[ -n "${OFFLINE_HOST_HOME:-}" ]]; then
    printf '%s\n' "${OFFLINE_HOST_HOME}"
    return 0
  fi
  if [[ -n "${HOME:-}" ]]; then
    printf '%s\n' "${HOME}"
    return 0
  fi
  local user_name
  user_name="$(id -un)"
  printf '/home/%s\n' "${user_name}"
}

offline_deployment_root() {
  if [[ -n "${DEPLOYMENT_ROOT:-}" ]]; then
    printf '%s\n' "${DEPLOYMENT_ROOT}"
    return 0
  fi
  printf '%s/nexuscrm-deployment\n' "$(offline_default_host_home)"
}

offline_host_env_root() {
  if [[ -n "${OFFLINE_HOST_ENV_ROOT:-}" ]]; then
    printf '%s\n' "${OFFLINE_HOST_ENV_ROOT}"
    return 0
  fi
  printf '%s\n' "$(offline_deployment_root)"
}

offline_envs_root() {
  if [[ -n "${OFFLINE_ENVS_ROOT:-}" ]]; then
    printf '%s\n' "${OFFLINE_ENVS_ROOT}"
    return 0
  fi
  printf '%s/offline/envs\n' "$(offline_deployment_root)"
}

offline_systemd_user() {
  printf '%s\n' "${SYSTEMD_USER:-$(id -un)}"
}

offline_base_env_file() {
  local env_name="$1"
  printf '%s/%s.ec2.env\n' "$(offline_host_env_root)" "${env_name}"
}

offline_backend_port() {
  local env_name="$1"
  local target="$2"
  case "${env_name}:${target}" in
    staging:single) printf '%s\n' 3101 ;;
    test:blue) printf '%s\n' 3105 ;;
    test:green) printf '%s\n' 3115 ;;
    ci:single) printf '%s\n' 3102 ;;
    exp:single) printf '%s\n' 3103 ;;
    *)
      echo "unsupported port mapping: ${env_name}:${target}" >&2
      return 1
      ;;
  esac
}

offline_runtime_env_name() {
  local env_name="$1"
  local target="$2"
  case "${target}" in
    single) printf '%s\n' "${env_name}" ;;
    blue|green) printf '%s-%s\n' "${env_name}" "${target}" ;;
    *)
      echo "unsupported runtime target: ${target}" >&2
      return 1
      ;;
  esac
}

offline_backend_service_name() {
  local env_name="$1"
  local target="$2"
  local runtime_env_name
  runtime_env_name="$(offline_runtime_env_name "${env_name}" "${target}")"
  printf 'nexuscrm-%s-backend.service\n' "${runtime_env_name}"
}

offline_set_kv() {
  local file="$1"
  local key="$2"
  local value="$3"
  local next_file="${file}.next"
  awk -v key="${key}" -v value="${value}" '
    BEGIN { replaced = 0 }
    index($0, key "=") == 1 {
      print key "=" value
      replaced = 1
      next
    }
    { print }
    END {
      if (replaced == 0) {
        print key "=" value
      }
    }
  ' "${file}" > "${next_file}"
  mv "${next_file}" "${file}"
}

offline_generate_deploy_id() {
  local env_name="$1"
  local target="$2"
  local stamp
  stamp="$(date -u +%Y%m%dT%H%M%SZ)"
  printf '%s-%s-%s\n' "${env_name}" "${target}" "${stamp}"
}

offline_env_value() {
  local file="$1"
  local key="$2"
  awk -F= -v key="${key}" '$1==key{print substr($0, index($0, "=")+1)}' "${file}" | tail -n 1
}

offline_require_runtime_env() {
  local file="$1"
  if [[ -z "${file}" || ! -f "${file}" ]]; then
    echo "runtime env file not found: ${file}" >&2
    return 1
  fi
}
