Files
openfreemap/scripts/http_host/nginx_sync/nginx_sync.py
2023-12-30 19:17:11 +01:00

101 lines
2.6 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import subprocess
import sys
from pathlib import Path
import click
RUNS_DIR = Path('/data/ofm/http_host/runs')
@click.command()
def cli():
if not Path('/etc/fstab').exists():
sys.exit('Needs to be run on Linux')
if os.geteuid() != 0:
sys.exit('Needs sudo')
if not Path('/mnt/ofm').exists():
sys.exit('mounter.py needs to be run first')
with open(Path(__file__).parent / 'nginx_template.conf') as fp:
nginx_template = fp.read()
location_block_str = ''
help_text = ''
for subdir in Path('/mnt/ofm').iterdir():
if not subdir.is_dir():
continue
area, version = subdir.name.split('-')
run_dir = RUNS_DIR / area / version
if not run_dir.is_dir():
print(f"{run_dir} doesn't exists, skipping")
continue
tilejson_path = run_dir / 'tilejson-tiles-org.json'
metadata_path = subdir / 'metadata.json'
if not metadata_path.is_file():
print(f"{metadata_path} doesn't exists, skipping")
continue
url_prefix = f'https://tiles.openfreemap.org/{area}/{version}/tiles//'
subprocess.run(
[
sys.executable,
Path(__file__).parent.parent / 'metadata_to_tilejson.py',
'--minify',
metadata_path,
tilejson_path,
url_prefix,
],
check=True,
)
version_str = rf"""
location /{area}/{version} {{ # no trailing hash
alias {tilejson_path}; # no trailing hash
add_header Cache-Control public;
expires 10y;
}}
location /{area}/{version}/ {{ # trailing hash
alias {subdir}/tiles/; # trailing hash
try_files $uri @empty;
add_header Cache-Control public;
expires 10y;
}}
"""
location_block_str += version_str
if not help_text:
help_text = (
'\ntest with:\n'
f'curl -H "Host: ofm" -I http://localhost/{area}/{version}/14/8529/5975.pbf'
)
nginx_template = nginx_template.replace('___LOCATION_BLOCKS___', location_block_str)
with open('/data/nginx/sites/ofm.conf', 'w') as fp:
fp.write(nginx_template)
print('nginx config written')
subprocess.run(['nginx', '-t'], check=True)
subprocess.run(['systemctl', 'reload', 'nginx'], check=True)
print(help_text)
if __name__ == '__main__':
cli()