#!/usr/bin/env python
# -*- coding: UTF-8 -*-

#    Simple thumbnail catalog generator 1.0 (c) Žarko Živanov 2012
#    zzarko account at gmail.com, lugons.org or uns.ac.rs

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

#    this script requires Python 2.7 and ImageMagick

VERSION="1.0"

import os
import sys
import shlex
import string
import subprocess
import argparse

def bash(command):
    """Helper function to execute bash commands"""
    command = shlex.split(command)
    try:
        code = subprocess.call(command, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
    except:
        code = 127
    return code

def error(text):
    print "%s\n" % text
    exit(1)

#collection path
COLLECTION = "~/PhotoCollection"
#image extensions
IMAGEEXT = "jpg,jpeg,png,bmp,tiff"
#thumbnail size
THUMBNAILW = 320
THUMBNAILH = 200

#check if imagemagick is installed
if bash("convert --version") > 0:
    error("To use this script, you need to install ImageMagick package")

#setup argument parser
description = """
Simple thumbnail catalog generator %s (c) Žarko Živanov 2012,
Chair for Applied Computer Science,
Faculty of Technical Sciences, Novi Sad http://www.acs.uns.ac.rs/,
member of Linux User Group of Novi Sad http://www.lugons.org/
""" % VERSION
about = """
This program replicates directory structure on requested media and generates thumbnails of image files it finds.
By default, it stores thumbnail collections in [%s] directory and searches for images with [%s] extensions.
Predefined thumbnail size is %dx%d. Example usage: if you put disc named "Travels 01" in your DVD drive
and run the script as %s /media/Travels\ 01/, you'll get thumbnails in ~/PhotoCollection/Travels\ 01/
(it is presumed that disc will be mounted with that name in /media directory).
""" %(COLLECTION,IMAGEEXT,THUMBNAILW,THUMBNAILH,sys.argv[0])
parser = argparse.ArgumentParser(description=description, epilog=about)
parser.add_argument('media', help='Path to the media containing images')
parser.add_argument('-n','--name', help='Collection name (if different from media name)',default="")
parser.add_argument('-c','--colpath', help='Path to the thumbnail collection directory',default=COLLECTION)
parser.add_argument('-e','--extensions', help='Comma separated image extensions to look for', default=IMAGEEXT)
parser.add_argument('-x','--thumbnailx', help='Thumbnail width', type=int, default=THUMBNAILW)
parser.add_argument('-y','--thumbnaily', help='Thumbnail height', type=int, default=THUMBNAILH)

#parse arguments
args = parser.parse_args()
collection = os.path.expanduser(args.colpath)
media = os.path.expanduser(args.media)
thumbw = args.thumbnailx
thumbh = args.thumbnaily
extensions = args.extensions.lower().split(',')
colname = args.name
if colname == "":
    path = media
    if path[-1] == "/": path = path[:-1]
    colname = os.path.basename(path)
colpath = os.path.join(collection,colname)

#check if collections directory exist
if not os.path.exists(collection):
    try:
        os.makedirs(collection)
    except:
        error("An error during creation of [%s] occured. Check your permissions." % collection)

#check if current collection's directory exist
if os.path.exists(colpath):
    error("Collection [%s] already exists in your collection directory!" % colname)
else:
    try:
        os.makedirs(colpath)
    except:
        error("An error during creation of [%s] occured. Check your permissions." % colpath)

#traverse the directories and generate thumbnails
if os.path.isdir(media):
    for dirpath, dirs, files in os.walk(media):
        currentpath = os.path.join(colpath,dirpath[len(media):])
        for directory in dirs:
            try:
                newdir = os.path.join(currentpath,directory)
                os.makedirs(newdir)
            except:
                error("An error during creation of [%s] occured. Check your permissions." % newdir)
        for picture in files:
            name,ext = os.path.splitext(picture)
            if ext != 0 and ext[0] == ".": ext = ext[1:]
            if ext.lower() in extensions:
                pic1 = os.path.join(dirpath,picture)
                pic2 = os.path.join(currentpath,name+'.jpg')
                print "Generating:",pic2
                ret = bash("convert \"%s\" -thumbnail %dx%d \"%s\"" % (pic1,thumbw,thumbh,pic2))
                if ret > 0:
                    error("An error occured during image conversion. Check your permissions.")
print "All done!\n"
exit(0)

