import 'dart:io'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:waylume_server/config/supabase_config.dart'; import 'package:waylume_server/core/utils.dart'; import 'package:waylume_server/services/rolling_codes_service.dart'; class ServerService { static Future registerServer() async { await RollingCodesService.initialize(); // Server always registers on startup to get fresh operational seed GeolocationData? geolocationData; try { geolocationData = await getGeolocationData(); } catch (e) { print('Warning: Failed to get geolocation data: $e'); print('Proceeding with registration without geolocation data'); } // Generate registration rolling code String registrationAuth = RollingCodesService.generateRegistrationCode(); print('Generated registration auth: $registrationAuth'); // Call server-manager registration endpoint String serverManagerUrl = 'https://lsdrctuvnwdrzrdyoqzu.supabase.co/functions/v1/server-manager'; Map requestBody = { 'server_id': fromEnivronment('SERVER_ID')!, "port": int.tryParse(fromEnivronment('EXTERNAL_PORT')) ?? 3000, 'registration_auth': registrationAuth, }; // Add geolocation data if available if (geolocationData != null) { requestBody['geolocation_data'] = { "country": geolocationData.countryName, "country_code": geolocationData.countryCode, "city": geolocationData.city, "coords": [ geolocationData.latitude, geolocationData.longitude ], }; } try { final response = await http.post( Uri.parse(serverManagerUrl), headers: { 'Content-Type': 'application/json', }, body: jsonEncode(requestBody), ); if (response.statusCode == 200) { final responseData = jsonDecode(response.body); if (responseData['success']) { // Store operational seed in memory (no persistence needed) RollingCodesService.setOperationalSeed(responseData['operational_seed']); print('Server registered successfully with server-manager'); return responseData['operational_seed']; } else { throw Exception('Registration failed: ${responseData['error']}'); } } else { throw Exception('Registration request failed: ${response.statusCode}'); } } catch (e) { print('Error registering server: $e'); throw Exception('Failed to register server: $e'); } } static Future isolatePeers() async { await Process.run('iptables', ['-I', 'FORWARD', '-i', 'wg0', '-o', 'wg0', '-j', 'DROP']); await Process.run('iptables', ['-I', 'FORWARD', '-i', 'wg0', '-o', 'wg0', '-m', 'state', '--state', 'ESTABLISHED,RELATED', '-j', 'ACCEPT']); } }