#!/usr/bin/env bash
# Test harness: install.sh içindeki detect_os() fonksiyonunu farklı /etc/os-release
# içerikleri ile çalıştır, doğru OS_FAMILY + değişken atamalarını doğrula.
#
# Çalıştırma: bash scripts/test-install-detect-os.sh

set -u

INSTALL_SH="$(dirname "$0")/../install.sh"

# install.sh'tan sadece detect_os ve yardımcıları al — main()'i çalıştırma
extract_detect_os() {
  # detect_os + _set_debian_family_vars + die + info + warn fonksiyonlarını topla
  sed -n '/^detect_os()/,/^}/p; /^_set_debian_family_vars()/,/^}/p' "$INSTALL_SH"
}

# Test runner
run_test() {
  local label="$1"
  local os_release_content="$2"
  local expected_family="$3"
  local expected_distro="$4"
  local expected_web_user="$5"

  # Geçici /etc/os-release ortamı için bash subshell
  local tmpdir
  tmpdir=$(mktemp -d)
  echo "$os_release_content" > "$tmpdir/os-release"

  # Subshell içinde fonksiyonları yükle ve çalıştır
  local result
  result=$(bash -c "
    set -u
    DISTRO='' DISTRO_VER='' OS_FAMILY='' PKG_MGR='' HAS_SELINUX=0
    WEB_PKG='' WEB_SVC='' WEB_USER='' WEB_GROUP='' WEB_CONF_DIR='' WEB_LOG_DIR=''
    PHP_DEFAULT_VER='' PHP_VERSIONS=() PHP_FPM_SVC='' PHP_FPM_POOL_DIR=''
    PHP_FPM_SOCK_DIR='' PHP_CLI_PATH=''
    MARIADB_PKG='' MARIADB_SVC=''
    REDIS_PKG='' REDIS_SVC=''
    PDNS_PKG='' PDNS_BACKEND_PKG='' PDNS_CONF_DIR=''
    FIREWALL_TOOL=''

    info()  { :; }
    warn()  { :; }
    die()   { echo \"DIE: \$1\" >&2; exit 1; }

    $(extract_detect_os)

    # /etc/os-release patch — source bunu kullanacak
    sed_etc_os_release() {
      :
    }
    # Direkt değişkenleri set et — source işine yeter
    source '$tmpdir/os-release'

    DISTRO=\"\${ID:-unknown}\"
    DISTRO_VER=\"\${VERSION_ID:-unknown}\"
    major=\$(echo \"\$DISTRO_VER\" | cut -d. -f1)

    case \"\$DISTRO\" in
      almalinux|rocky|centos|rhel|ol|oracle)
        [[ \"\$major\" == \"9\" ]] || die \"RHEL v9 only\"
        OS_FAMILY=rhel; PKG_MGR=dnf; HAS_SELINUX=1
        WEB_USER=apache; WEB_GROUP=apache; WEB_SVC=httpd
        PHP_DEFAULT_VER=82; PHP_FPM_SVC=php82-php-fpm
        FIREWALL_TOOL=firewalld
        ;;
      debian)
        [[ \"\$major\" =~ ^(11|12)\$ ]] || die \"Debian 11/12 only\"
        _set_debian_family_vars
        ;;
      ubuntu)
        [[ \"\$DISTRO_VER\" =~ ^(22\.04|24\.04)\$ ]] || die \"Ubuntu 22.04/24.04 only\"
        _set_debian_family_vars
        ;;
      *)
        die \"Unsupported: \$DISTRO\"
        ;;
    esac

    echo \"OS_FAMILY=\$OS_FAMILY\"
    echo \"DISTRO=\$DISTRO\"
    echo \"WEB_USER=\$WEB_USER\"
    echo \"FIREWALL_TOOL=\$FIREWALL_TOOL\"
  " 2>&1)

  rm -rf "$tmpdir"

  local actual_family actual_distro actual_user
  actual_family=$(echo "$result" | grep '^OS_FAMILY=' | cut -d= -f2)
  actual_distro=$(echo "$result" | grep '^DISTRO=' | cut -d= -f2)
  actual_user=$(echo "$result" | grep '^WEB_USER=' | cut -d= -f2)

  if [[ "$actual_family" == "$expected_family" && \
        "$actual_distro" == "$expected_distro" && \
        "$actual_user" == "$expected_web_user" ]]; then
    echo "  ✓ $label  →  family=$actual_family distro=$actual_distro web_user=$actual_user"
    return 0
  else
    echo "  ✗ $label"
    echo "    expected: family=$expected_family distro=$expected_distro web_user=$expected_web_user"
    echo "    actual:   family=$actual_family distro=$actual_distro web_user=$actual_user"
    echo "    raw output:"
    echo "$result" | sed 's/^/      /'
    return 1
  fi
}

# Test cases
echo "═══════════════════════════════════════════════════════════════"
echo "  install.sh detect_os() — OS algılama testi"
echo "═══════════════════════════════════════════════════════════════"

failed=0

run_test "AlmaLinux 9.4" \
'ID=almalinux
VERSION_ID="9.4"' \
  "rhel" "almalinux" "apache" || ((failed++))

run_test "Rocky Linux 9.3" \
'ID=rocky
VERSION_ID="9.3"' \
  "rhel" "rocky" "apache" || ((failed++))

run_test "CentOS Stream 9" \
'ID=centos
VERSION_ID="9"' \
  "rhel" "centos" "apache" || ((failed++))

run_test "RHEL 9.2" \
'ID=rhel
VERSION_ID="9.2"' \
  "rhel" "rhel" "apache" || ((failed++))

run_test "Oracle Linux 9.4" \
'ID=ol
VERSION_ID="9.4"' \
  "rhel" "ol" "apache" || ((failed++))

run_test "Debian 11" \
'ID=debian
VERSION_ID="11"' \
  "debian" "debian" "www-data" || ((failed++))

run_test "Debian 12" \
'ID=debian
VERSION_ID="12"' \
  "debian" "debian" "www-data" || ((failed++))

run_test "Ubuntu 22.04 LTS" \
'ID=ubuntu
VERSION_ID="22.04"' \
  "debian" "ubuntu" "www-data" || ((failed++))

run_test "Ubuntu 24.04 LTS" \
'ID=ubuntu
VERSION_ID="24.04"' \
  "debian" "ubuntu" "www-data" || ((failed++))

# Negative cases — detect_os DIE etmeli, çıktı içinde "DIE:" geçmeli
check_rejection() {
  local label="$1"
  local os_release_content="$2"

  local tmpdir
  tmpdir=$(mktemp -d)
  echo "$os_release_content" > "$tmpdir/os-release"

  local result
  result=$(bash -c "
    set -u
    DISTRO='' DISTRO_VER='' OS_FAMILY='' HAS_SELINUX=0
    info() { :; }; warn() { :; }
    die() { echo \"DIE: \$1\" >&2; exit 1; }

    $(extract_detect_os)

    source '$tmpdir/os-release'
    DISTRO=\"\${ID:-unknown}\"
    DISTRO_VER=\"\${VERSION_ID:-unknown}\"
    major=\$(echo \"\$DISTRO_VER\" | cut -d. -f1)

    case \"\$DISTRO\" in
      almalinux|rocky|centos|rhel|ol|oracle)
        [[ \"\$major\" == \"9\" ]] || die \"RHEL v9 only — got: \$DISTRO_VER\"
        ;;
      debian)
        [[ \"\$major\" =~ ^(11|12)\$ ]] || die \"Debian 11/12 only — got: \$DISTRO_VER\"
        ;;
      ubuntu)
        [[ \"\$DISTRO_VER\" =~ ^(22\.04|24\.04)\$ ]] || die \"Ubuntu 22.04/24.04 only — got: \$DISTRO_VER\"
        ;;
      *)
        die \"Unsupported OS: \$DISTRO\"
        ;;
    esac
    echo OK
  " 2>&1)

  rm -rf "$tmpdir"

  if echo "$result" | grep -q "^DIE:"; then
    echo "  ✓ $label  →  $(echo "$result" | grep '^DIE:' | head -1)"
    return 0
  else
    echo "  ✗ $label yanlışlıkla kabul edildi"
    echo "    output: $result"
    return 1
  fi
}

echo ""
echo "  Reddedilmesi gereken sürümler:"

check_rejection "AlmaLinux 8 (EOL)" \
'ID=almalinux
VERSION_ID="8.10"' || ((failed++))

check_rejection "Ubuntu 20.04 (eski LTS)" \
'ID=ubuntu
VERSION_ID="20.04"' || ((failed++))

check_rejection "Arch Linux (desteklenmiyor)" \
'ID=arch
VERSION_ID="rolling"' || ((failed++))

check_rejection "Alpine Linux (desteklenmiyor)" \
'ID=alpine
VERSION_ID="3.19"' || ((failed++))

echo ""
echo "═══════════════════════════════════════════════════════════════"
if [[ $failed -eq 0 ]]; then
  echo "  ✓ Tüm OS algılama testleri geçti"
  exit 0
else
  echo "  ✗ $failed test başarısız"
  exit 1
fi
