"""Build the production database"""

from Crypto.Cipher import AES
import hashlib
import json
import subprocess

# This here is a hack
import sys
sys.path.extend('..')
from app import db, Category, Flag, Team


def load_passwords(in_file):
    with subprocess.Popen(['/usr/bin/openssl', 'enc', '-d', '-aes-256-cbc'],
        stdin=in_file, stdout=subprocess.PIPE) as proc:
        for p in proc.stdout:
            yield hashlib.sha256(p.strip()).hexdigest()


def main(argv):
    if len(argv) < 4 :
        sys.stderr.write('Usage: python prod_scores.py ORDER SCORES PASSWORDS\n')
        return 1
    with open(argv[2], 'r') as score_file:
        scores = json.load(score_file)
        wargame = scores['wargame']
        points = sorted([(int(k), v) for k, v in scores['PointsByLevel'].items()])
    with open(argv[3], 'rb') as pw_file:
        passwords = load_passwords(pw_file)
        db.create_all()
        cat = Category(name=wargame, order=int(argv[1]))
        db.session.add(cat)
        for level, flag_hash in enumerate(passwords):
            flag = Flag(hash=flag_hash, level=level, category=cat, points=points[level][1])
            db.session.add(flag)
        db.session.commit()
        return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv))

@@ -196,16 +196,23 @@
 y, Flag,
+ Level,
  Team%0A%0A%0A
@@ -388,14 +388,27 @@
  for
+ i,
  p in 
+enumerate(
 proc
@@ -414,16 +414,17 @@
 c.stdout
+)
 :%0A      
@@ -433,13 +433,186 @@
     
-yield
+p = p.strip()%0A            if b' ' in p:%0A                lev, fleg = p.split(' ', 1)%0A            else:%0A                lev = i%0A                fleg = p%0A            yield int(lev),
  has
@@ -623,25 +623,20 @@
 .sha256(
-p.strip()
+fleg
 ).hexdig
@@ -911,81 +911,344 @@
     
-points = sorted(%5B(int(k), v) for k, v in scores%5B'PointsByLevel'%5D.items()%5D
+cat = Category(name=wargame, order=int(argv%5B1%5D), enforce=scores.get('enforce_order', False))%0A        levels = %5B%5D%0A        for level, points in sorted(%5B(int(k), v) for k, v in scores%5B'PointsByLevel'%5D.items()%5D):%0A            lev = Level(category=cat, level=level, points=points)%0A            levels.append(lev)%0A            db.session.add(lev
 )%0A  
@@ -1358,65 +1358,8 @@
 l()%0A
-        cat = Category(name=wargame, order=int(argv%5B1%5D))%0A
     
@@ -1397,18 +1397,16 @@
  for lev
-el
 , flag_h
@@ -1412,26 +1412,16 @@
 hash in 
-enumerate(
 password
@@ -1421,17 +1421,16 @@
 asswords
-)
 :%0A      
@@ -1478,46 +1478,13 @@
 evel
-, category=cat, points=points%5Blevel%5D%5B1
+s%5Blev
 %5D)%0A 

Update prod_scores.py