#!/usr/bin/python
import os
import shutil
import sys

CMD = 'LD_LIBRARY_PATH=/usr/local/lib fprint_demo'
PRINTS_DIR = os.path.join(
    os.path.expanduser('~'), '.fprint', 'prints')
RESULTS_DIR = os.path.join(
    os.path.expanduser('~'), 'fingerprints')


def get_first_dir(path):
    """Get first available path in `path`.

    For instance if `path` is the directory ``/a/b/`` and contains the
    files/directories ``c``, ``d``, ``e``, then this function will
    return ``/a/b/c``.
    """
    name = ''
    if path is None or not os.path.exists(path):
        print "Doesn't exist: ", path
        return None
    try:
        name = sorted(os.listdir(path))[0]
    except:
        return None
    return os.path.join(path, name)


def get_stud_id():
    """Get a student id via input from keyboard.

    We require the id two times (for safety). The id must have length 8.
    """
    while True:
        stud_id = raw_input("Please ENTER the STUDENT ID: ")
        if len(stud_id) != 8:
            print "Please enter a valid student ID!"
        else:
            ctrl_id = raw_input("Please repeat              : ")
            if stud_id != ctrl_id:
                print "IDs do not match. We restart."
            else:
                return stud_id


# create results dir if it does not exist already.
if not os.path.exists(RESULTS_DIR):
    print "Creating dir for collected fingerprints in %s" % RESULTS_DIR
    os.mkdir(RESULTS_DIR)

print
print "After entering a student ID, the fingerprint scanner GUI will"
print "appear. Then, please do a scan ('enroll') of a finger via the GUI."
print
print "After scanning, please close the scanner programme."
print

if os.path.exists(PRINTS_DIR):
    shutil.rmtree(PRINTS_DIR)

stud_id = get_stud_id()

os.system(CMD)

fp_file = get_first_dir(get_first_dir(get_first_dir(PRINTS_DIR)))
if fp_file is None or not os.path.isfile(fp_file):
    print "ERROR: No fingerprint generated. Exiting."
    sys.exit(0)

basename = os.path.basename(fp_file)

student_path = os.path.join(RESULTS_DIR, stud_id.upper())
fp_target = os.path.join(student_path, basename)
if not os.path.exists(student_path):
    # create a dir for each student
    os.mkdir(student_path)

print "COPYING fingerprint over..."
if os.path.isfile(fp_target):
    # such a fingerprint exists already (same finger, stud_id)
    os.unlink(fp_target)
shutil.copy2(fp_file, fp_target)

print "DONE. Thanks for using enroll_script.py."
print "Collected prints are in %s" % RESULTS_DIR
