import subprocess, json, sys, os

jsn = subprocess.check_output("calibredb list -f title,tags --for-machine", shell=True)
dic = json.loads(jsn)

for book in dic:
   if book["title"] in book["tags"]:
      print "Found title in the tags of: " + book["title"]
      newTags = book["tags"]
      newTags.remove(book["title"])
      tagStr = ",".join(newTags)
      cmd = "calibredb set_metadata --field tags:\"" + tagStr + "\" " + str(book["id"])
      try:
         if sys.argv[1] == "overwrite":
            os.system(cmd)
      except:
         pass
