"""Applies the fixes to a copy of the vulnerable snapshot and writes fixed_account.json."""
import json, copy, sys

def fix(a):
    a = copy.deepcopy(a)
    for b in a["s3_buckets"]:
        b["PublicAccessBlock"] = {"BlockPublicPolicy": True, "RestrictPublicBuckets": True}
        b["Policy"] = None                       # public statement removed; share via CloudFront / presigned URLs
        b["Encryption"] = b["Encryption"] or "aws:kms"
    for u in a["iam_users"]:
        if u["UserName"] == "dev-intern":
            u["Policies"] = [{"PolicyName": "intern-scoped", "Document": {"Version": "2012-10-17", "Statement": [
                {"Effect": "Allow", "Action": ["s3:GetObject", "s3:ListBucket"], "Resource": ["arn:aws:s3:::lab-private-backups", "arn:aws:s3:::lab-private-backups/*"]}]}}]
    for g in a["security_groups"]:
        for p in g["IpPermissions"]:
            if p["FromPort"] == 22:
                p["IpRanges"] = [{"CidrIp": "10.20.0.0/24"}]       # the VPN range in this lab
        g["IpPermissions"] = [p for p in g["IpPermissions"] if p["FromPort"] != 3306]  # DB only reachable inside the VPC
    for fn in a["lambda_functions"]:
        v = fn["Environment"]["Variables"]
        if "DB_PASSWORD" in v:
            del v["DB_PASSWORD"]; v["DB_SECRET_ARN"] = "arn:aws:secretsmanager:us-east-1:111122223333:secret:lab/db-AbCdEf"
    for vol in a["ebs_volumes"]:
        vol["Encrypted"] = True                  # in real life: snapshot -> encrypted copy -> new volume -> swap
    for r in a["iam_roles"]:
        if r["RoleName"] == "app-cross-account":
            r["AssumeRolePolicyDocument"] = {"Version": "2012-10-17", "Statement": [{
                "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::444455556666:root"}, "Action": "sts:AssumeRole",
                "Condition": {"StringEquals": {"sts:ExternalId": "lab-partner-7f3a"}}}]}
    for t in a["cloudtrail_trails"]:
        t["IsLogging"] = True; t["IsMultiRegionTrail"] = True
    return a

if __name__ == "__main__":
    src = json.load(open("lab_data/vulnerable_account.json"))
    json.dump(fix(src), open("lab_data/fixed_account.json", "w"), indent=2)
    print("wrote lab_data/fixed_account.json")
