#!/usr/bin/env python3
from pathlib import Path
import re, sqlite3
app=Path('/srv/apps/sotlab-users/sotlab_users_app.py')
print('--- perms/content available ---')
print(app, app.exists())
text=app.read_text()
for start,end in [(1,120),(250,305),(500,590)]:
    print(f'--- lines {start}-{end} sanitized ---')
    for i,line in enumerate(text.splitlines()[start-1:end], start):
        if re.search(r'def do_POST|def authenticate|def user_can_access|profile_enabled|profile_services|path ==|set_session|HOST_SERVICE|sotlab.co.uk|login|portal|service', line, re.I):
            line=re.sub(r'(password|hash|secret|token)([^\s]*)', r'\1_REDACTED', line, flags=re.I)
            print(f'{i}:{line}')
print('--- db profile safe summary ---')
con=sqlite3.connect('/srv/apps/sotlab-users/data/users.sqlite3')
con.row_factory=sqlite3.Row
print('tables', [r[0] for r in con.execute("select name from sqlite_master where type='table' order by name")])
print('profile columns', [r[1] for r in con.execute('pragma table_info(profiles)')])
for row in con.execute("""
select p.id,p.username,p.profile_enabled,
       case when coalesce(p.password_hash,'')='' then 0 else 1 end has_password,
       count(case when ps.enabled=1 then 1 end) enabled_services,
       group_concat(case when ps.enabled=1 then ps.service_key end) services
from profiles p
left join profile_services ps on ps.profile_id=p.id
group by p.id,p.username,p.profile_enabled,p.password_hash
order by p.username
"""):
    print(dict(row))
