summaryrefslogtreecommitdiff
path: root/simpleddns.py
blob: 19196ce5440752a3eb7e56e8861b9dc33579fcfa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python3
import os
import sys
import requests
import stat
import subprocess
from pathlib import Path

simpleddns_config_dir = os.getenv('SIMPLEDDNS_CONFIG_DIR')
xdg_config_dir = os.getenv('XDG_CONFIG_DIR')
if simpleddns_config_dir:
	config_dir = Path(simpleddns_config_dir)
elif xdg_config_dir:
	config_dir = Path(xdg_config_dir, 'simpleddns')
else:
	config_dir = Path('~/.config/simpleddns').expanduser()
os.makedirs(config_dir, exist_ok = True)

def fatal_error(message):
	sys.stderr.write(f'Fatal error: {message}\n')
	exit(1)

get_ip_path = Path(config_dir, 'getip')

if not get_ip_path.exists():
	print(f'Warning: {get_ip_path} does not exist. Putting default of "curl ifconfig.co" there')
	with open(get_ip_path, 'w') as f:
		f.write('curl --no-progress-meter ifconfig.co')

def get_ip():
	if os.name == 'posix' and (get_ip_path.stat().st_mode & 0o100):
		command = str(get_ip_path)
	else:
		command = open(get_ip_path).read()
	result = subprocess.run(command, shell=True, stdout=subprocess.PIPE)
	if result.returncode:
		print(f'WARNING: {command} failed (exit code {result.returncode})')
		return None
	return result.stdout.decode(errors='replace').strip()

print(get_ip())