#!/usr/bin/env python
#
# This script cleans the Instant cache

__author__ = "Ilmar Wilbers (ilmarw@simula.no)"
__date__ = "2008-08-08 -- 2008-09-01"
__copyright__ = "Copyright (C) 2008 Ilmar Wilbers"
__license__  = "GNU GPL version 3 or any later version"

# Modified by Martin Alnes

import os, sys, shutil, glob, re
try:
    import instant
except:
    print "Instant not installed, exiting..."
    sys.exit(1)

# Check if any temp directories exists
tmp = instant.get_temp_dir()
tmp_dir_prefix = os.path.split(tmp)[0]
s = re.search(r"(.*)%s[^%s]*instant" % (os.path.pathsep, os.path.pathsep), tmp) # FIXME: Is it safe to assume that the prefix to tempdirs is constant on a platform?
instant.delete_temp_dir()
tmp_dirs = glob.glob(os.path.join(tmp_dir_prefix, '*instant'))
for d in tmp_dirs:
    if os.path.isdir(d):
        print "Deleting temp directory", d
        shutil.rmtree(d, ignore_errors=True)

# Get default cache dir (won't and can't touch userdefined cache dirs in this script)
cache_dir = instant.get_default_cache_dir()

# Check if directory exists (it always should after calling get_default_cache_dir)
assert os.path.isdir(cache_dir)

# Get list of cached forms
modules = os.listdir(cache_dir)
if len(modules) == 0:
    print "Instant cache is empty"
    sys.exit(0)

# Remove cached forms
lockfiles = [m for m in modules if     m.endswith(".lock")]
modules   = [m for m in modules if not m.endswith(".lock")]
print "Removing %d modules from Instant cache..." % len(modules)
for module in modules:
    directory = os.path.join(cache_dir, module)
    shutil.rmtree(directory, ignore_errors=True)

print "Removing %d lock files from Instant cache..." % len(lockfiles)
for lf in lockfiles:
    f = os.path.join(cache_dir, lf)
    os.remove(f)
