"""Extract medilad-orig.zip (Windows backslash paths, top folder medinetbd_cpanel)
directly into the deploy dir with fixed Unix paths. Run on the server via:
  cd /home/medinetb/public_html/medilad && python3 fixzip.py
"""
import zipfile
import os

SRC = '/home/medinetb/public_html/medilad/medilad-orig.zip'
DST = '/home/medinetb/public_html/medilad'
PREFIX = 'medinetbd_cpanel/'

z = zipfile.ZipFile(SRC)
files = dirs = skipped = 0
for info in z.infolist():
    name = info.filename.replace('\\', '/')
    if not name.startswith(PREFIX):
        skipped += 1
        continue
    rel = name[len(PREFIX):]
    if not rel:
        continue
    target = os.path.join(DST, rel)
    if name.endswith('/'):
        os.makedirs(target, exist_ok=True)
        os.chmod(target, 0o755)
        dirs += 1
    else:
        os.makedirs(os.path.dirname(target), exist_ok=True)
        with open(target, 'wb') as f:
            f.write(z.read(info.filename))
        os.chmod(target, 0o644)
        files += 1
print('files:', files, 'dirs:', dirs, 'skipped:', skipped)
# key paths writable for Laravel
for p in ('storage', 'bootstrap/cache'):
    full = os.path.join(DST, p)
    if os.path.isdir(full):
        for root, dnames, fnames in os.walk(full):
            os.chmod(root, 0o775)
            for fn in fnames:
                os.chmod(os.path.join(root, fn), 0o664)
print('writable perms set on storage/ and bootstrap/cache')
