#!/usr/bin/env python

# Copyright: 2015 The Debian Project
# License: MIT-License or Apache-2.0

from __future__ import print_function
from glob import glob
import json
import os
import os.path
import shutil
import sys

CHECKSUM_FILENAME = ".cargo-checksum.json"
CHECKSUM_FILES = dict()

def ensure_loaded_checksum_file_for_crate(root, crate):
  if crate in CHECKSUM_FILES:
    return

  with open(os.path.join(root, crate, CHECKSUM_FILENAME), "r") as f:
    CHECKSUM_FILES[crate] = json.load(f)

def remove_checksum_for_file(root, file):
  relpath = os.path.relpath(file, root)
  relpath_parts = relpath.split(os.sep)
  crate = relpath_parts[0]
  ensure_loaded_checksum_file_for_crate(root, crate)

  del CHECKSUM_FILES[crate]["files"][os.sep.join(relpath_parts[1:]).decode("utf-8")]

def remove_one_path(root, path):
  if os.path.isdir(path):
    for dir, dirs, files in os.walk(path):
      for f in files:
        remove_checksum_for_file(root, os.path.join(dir, f))
  else:
    remove_checksum_for_file(root, path)

  shutil.rmtree(path)

def process_filter(root, entry):
  for i in glob(os.path.join(root, entry)):
    remove_one_path(root, i)

def main():
  if len(sys.argv) != 2:
    print("usage: fix-cargo-checksums.py <filter>", file=sys.stderr)
    sys.exit(1)

  root = os.path.join(os.getcwd(), "vendor")
  if not os.path.isdir(root):
    print("Path '%s' doesn't exist. Are you in the wront directory?" % root, file=sys.stderr)
    sys.exit(1)

  filter_file = sys.argv[1]

  with open(filter_file, "r") as f:
    for l in f.readlines():
      l = l.strip()
      if l.startswith("#") or l == "":
        continue
      process_filter(root, l)

  for k, v in CHECKSUM_FILES.iteritems():
    with open(os.path.join(root, k, CHECKSUM_FILENAME), "w") as f:
      f.write(json.dumps(v))

if __name__ == "__main__":
  main()
