#!/usr/bin/env python3
"""Private single-copy physical staging. PostgreSQL 11 has a separate receipt;
it is never represented as a native PostgreSQL backup_manifest."""
import hashlib,json,os,pathlib,re,shutil,stat,subprocess,sys,time

os.umask(0o077)
os.environ['LC_ALL']='C'
directory=pathlib.Path(os.environ.get('PG_BIN_DIR','/usr/bin'))
def tool(name,*args,**kw):
    return subprocess.run([str(directory/name),*map(str,args)],check=True,**kw)
def digest(path):
    fd=os.open(str(path),os.O_RDONLY|os.O_NOFOLLOW)
    try:
        before=os.fstat(fd);assert stat.S_ISREG(before.st_mode),'non-regular backup file'
        h=hashlib.sha256()
        with os.fdopen(os.dup(fd),'rb') as f:
            for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
        after=os.fstat(fd)
        assert (before.st_size,before.st_mtime_ns,before.st_ctime_ns)==(after.st_size,after.st_mtime_ns,after.st_ctime_ns),'backup changed during validation'
        return before.st_size,h.hexdigest()
    finally:os.close(fd)
def files(cluster):
    assert cluster.is_dir() and not cluster.is_symlink()
    for root,dirs,names in os.walk(str(cluster),followlinks=False):
        dirs.sort();names.sort()
        for name in dirs:assert not pathlib.Path(root,name).is_symlink(),'symlink directory refused'
        for name in names:
            path=pathlib.Path(root,name)
            assert stat.S_ISREG(path.lstat().st_mode),'non-regular backup file refused'
            yield path.relative_to(cluster).as_posix(),path
def structure(cluster):
    assert not (cluster/'PG_VERSION').is_symlink()
    major=(cluster/'PG_VERSION').read_text().strip()
    assert major in ('11','13','14','15','16','17','18'),'unsupported PostgreSQL major'
    for name in ('pg_wal','pg_tblspc'):
        path=cluster/name;assert path.is_dir() and not path.is_symlink()
    assert not list((cluster/'pg_tblspc').iterdir()),'external tablespaces not yet supported'
    # Reject links/special files before invoking tools that read pg_control or
    # native manifests. Never allow restored metadata to redirect those reads.
    for name,path in files(cluster):pass
    return major
def control(cluster):
    p=tool('pg_controldata',cluster,universal_newlines=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    assert not p.stderr.strip(),'pg_control validation warning'
    def value(label):
        match=re.search('^'+re.escape(label)+r':\s*(\d+)\s*$',p.stdout,re.M)
        assert match,'missing pg_control field: '+label
        return int(match.group(1))
    return value('Database system identifier'),value('Bytes per WAL segment')
def sanitize_standby11(cluster):
    # PostgreSQL 11 includes the standby's recovery.conf in a base backup.
    # It can contain credentials and would reconnect a restored copy upstream.
    path=cluster/'recovery.conf'
    assert stat.S_ISREG(path.lstat().st_mode),'standby recovery.conf must be a regular file'
    path.unlink()
def interval(cluster,end):
    label=(cluster/'backup_label').read_text()
    m=re.match(r'START WAL LOCATION: ([0-9A-F]+/[0-9A-F]+) \(file ([0-9A-F]{24})\)\n',label)
    assert m,'invalid backup_label'
    start,name=m.groups();timeline=int(name[:8],16)
    def lsn(x):a,b=x.split('/');return int(a,16)*2**32+int(b,16)
    assert lsn(end)>lsn(start),'empty WAL interval'
    tool('pg_waldump','-p',cluster/'pg_wal','-t',timeline,'-s',start,'-e',end,'-z',stdout=subprocess.DEVNULL)
    return start,timeline
def receipt(stage,end):
    cluster=stage/'cluster';structure(cluster);system,segsize=control(cluster)
    start,timeline=interval(cluster,end)
    manifest=stage/'pg11-files.jsonl'
    begin=time.monotonic();reported=begin;total=0;count=0
    print('postgresql_prepare phase=hashing_files',file=sys.stderr,flush=True)
    with manifest.open('w') as out:
        for name,path in files(cluster):
            size,h=digest(path);out.write(json.dumps([name,size,h],ensure_ascii=True,separators=(',',':'))+'\n')
            total+=size;count+=1;now=time.monotonic()
            if now-reported>=30:
                print('postgresql_hash bytes=%d files=%d seconds=%.3f'%(total,count,now-begin),file=sys.stderr,flush=True);reported=now
        out.flush();os.fsync(out.fileno())
    text='SCHIPPG11 1\nsystem_identifier=%d\ntimeline=%d\nstart_lsn=%s\nend_lsn=%s\nwal_segment_size=%d\nfile_manifest_sha256=%s\n'%(system,timeline,start,end,segsize,digest(manifest)[1])
    with (stage/'pg11-receipt.txt').open('w') as out:out.write(text);out.flush();os.fsync(out.fileno())
def verify(stage):
    cluster=stage/'cluster';major=structure(cluster)
    if major!='11':
        version=tool('pg_verifybackup','--version',universal_newlines=True,stdout=subprocess.PIPE).stdout
        assert re.match(r'pg_verifybackup \(PostgreSQL\) '+major+r'\.',version),'verification tool major mismatch'
        tool('pg_verifybackup',cluster,stdout=sys.stderr);return
    version=tool('pg_waldump','--version',universal_newlines=True,stdout=subprocess.PIPE).stdout
    assert re.match(r'pg_waldump \(PostgreSQL\) 11\.',version),'verification tool major mismatch'
    receipt_path=stage/'pg11-receipt.txt'
    assert stat.S_ISREG(receipt_path.lstat().st_mode) and receipt_path.stat().st_size<=1024
    text=receipt_path.read_text()
    m=re.fullmatch(r'SCHIPPG11 1\nsystem_identifier=(\d+)\ntimeline=(\d+)\nstart_lsn=([0-9A-F]+/[0-9A-F]+)\nend_lsn=([0-9A-F]+/[0-9A-F]+)\nwal_segment_size=(\d+)\nfile_manifest_sha256=([0-9a-f]{64})\n',text)
    assert m,'invalid PostgreSQL 11 receipt'
    system,tli,start,end,segsize,h=m.groups();manifest=stage/'pg11-files.jsonl'
    assert control(cluster)==(int(system),int(segsize)),'cluster identity mismatch'
    assert digest(manifest)[1]==h,'file manifest checksum mismatch'
    with manifest.open() as stream:
        for name,path in files(cluster):
            line=stream.readline(65537);assert len(line)<=65536,'oversized file manifest entry'
            expected=json.loads(line);size,checksum=digest(path)
            assert expected==[name,size,checksum],'missing, added or corrupt backup file: '+name
        assert not stream.read(1),'extra file manifest entries'
    assert interval(cluster,end)==(start,int(tli)),'WAL interval mismatch'
def prepare(stage):
    bwrap=shutil.which('bwrap');assert bwrap,'bubblewrap required; unsafe plain-mode fallback refused'
    assert stage.is_dir() and not stage.is_symlink() and stat.S_IMODE(stage.stat().st_mode)==0o700
    binary=(directory/'pg_basebackup').resolve(strict=True)
    version=tool('pg_basebackup','--version',universal_newlines=True,stdout=subprocess.PIPE).stdout
    m=re.match(r'pg_basebackup \(PostgreSQL\) (11|13|14|15|16|17|18)\.',version)
    assert m,'unsupported pg_basebackup version';major=m.group(1)
    args=[str(binary),'--no-password','--format=plain','--wal-method=stream','--verbose','--progress','--checkpoint='+os.environ.get('PG_BASE_CHECKPOINT','spread'),'--pgdata='+str(stage/'cluster')]
    rate=os.environ.get('PG_BASE_MAX_RATE','')
    if rate:
        assert re.fullmatch(r'[1-9][0-9]*[kM]?',rate),'invalid PG_BASE_MAX_RATE'
        args+=['--max-rate='+rate]
    if major!='11':args+=['--manifest-checksums=SHA256']
    # Unprivileged callers need a user namespace. Root keeps the host user
    # namespace for ZFS bind-mount compatibility, but drops ALL capabilities
    # before executing the receiver: neither path can remount the host writable.
    sandbox=[bwrap,'--die-with-parent']+(['--unshare-user'] if os.geteuid()!=0 else [])+['--unshare-pid','--cap-drop','ALL','--ro-bind','/','/','--bind',str(stage),str(stage),'--proc','/proc','--dev','/dev','--chdir',str(stage)]
    begin=time.monotonic()
    print('postgresql_prepare phase=receiving_base max_rate='+rate,file=sys.stderr,flush=True)
    with (stage/'basebackup.log').open('w+') as log:
        result=subprocess.run(sandbox+args,stdout=sys.stderr,stderr=log)
        if result.returncode:
            log.flush();log.seek(0,os.SEEK_END);size=log.tell();log.seek(max(0,size-4096))
            print(log.read(),file=sys.stderr)
            result.check_returncode()
    structure(stage/'cluster')
    standby=os.environ.get('PG_SOURCE_STANDBY','0')
    assert standby in ('0','1'),'invalid PG_SOURCE_STANDBY'
    if standby=='1':
        assert major=='11','standby sanitization currently supports PostgreSQL 11 only'
        sanitize_standby11(stage/'cluster')
    print('postgresql_prepare phase=validating_base',file=sys.stderr,flush=True)
    if major=='11':
        log=(stage/'basebackup.log').read_text();ends=re.findall(r'write-ahead log end point: ([0-9A-F]+/[0-9A-F]+)',log)
        assert len(ends)==1,'authoritative backup end LSN missing'
        receipt(stage,ends[0])
    else:verify(stage)
    (stage/'client-version.txt').write_text(version)
    print('postgresql_prepare layout=plain copies=1 major=%s seconds=%.6f'%(major,time.monotonic()-begin),file=sys.stderr)
if __name__=='__main__':
    assert len(sys.argv)==3 and sys.argv[1] in ('prepare','verify')
    stage=pathlib.Path(sys.argv[2]).resolve(strict=True)
    (prepare if sys.argv[1]=='prepare' else verify)(stage)
