# run: python3 patch.py  (backs up /opt/hist/rh_rebuild.py, patches pick() oldest-first + RH_LITE flag, then restart rh_rebuild.py)
import shutil,time
p='/opt/hist/rh_rebuild.py'; shutil.copy(p,p+'.bak_ppdata_'+time.strftime('%H%M')); s=open(p).read()
a='''    t = yday
    while t >= first:
        p = "%s/%s.db" % (OUTD, dayname(t))
        if not os.path.exists(p): return t, "new"
        c = db(p); ok = done(c, "complete"); c.close()
        if not ok: return t, "new"
        t -= 86400
'''
b='''    t = yday; miss = None
    while t >= first:      # 27 Oct: OLDEST incomplete day first; complete_lite = swaps6h only
        p = "%s/%s.db" % (OUTD, dayname(t))
        if not os.path.exists(p): miss = t
        else:
            c = db(p); ok = done(c, "complete") or done(c, "complete_lite"); c.close()
            if not ok: miss = t
        t -= 86400
    if miss is not None: return miss, "new"
'''
assert a in s; s=s.replace(a,b)
a='''                stage_a(day, b0, b1, c); stage_b(day, b0, b1, c, head)
'''
b='''                lite = os.path.exists("/opt/hist/RH_LITE") and day_t < (int(time.time() + 7 * 3600) // 86400 - 2) * 86400 - 7 * 3600
                stage_a(day, b0, b1, c, lite)
                if lite:
                    mark(c, "complete_lite", int(time.time())); log("%s LITE DONE in %d min" % (day, (time.time() - t) / 60)); c.close(); continue
                stage_b(day, b0, b1, c, head)
'''
assert a in s; s=s.replace(a,b)
s=s.replace('def stage_a(day, b0, b1, c):','def stage_a(day, b0, b1, c, lite=False):')
s=s.replace('    if not done(c, "tapes"):\n','    if not lite and not done(c, "tapes"):\n',1)
open(p,'w').write(s)
