]> git.draconx.ca Git - mpdhacks.git/blob - thumbnail.zsh
thumbnailer: Follow only one level of symbolic link.
[mpdhacks.git] / thumbnail.zsh
1 #!/usr/bin/env zsh
2 #
3 # Copyright © 2008, 2017 Nick Bowler
4 #
5 # Simple thumbnail generator for use with FVWM.  Thumbnails can be generated at
6 # any desired size, and are cached for future use.  Prints the cached filename
7 # to standard output.
8 #
9 # License WTFPL2: Do What The Fuck You Want To Public License, version 2.
10 # This is free software: you are free to do what the fuck you want to.
11 # There is NO WARRANTY, to the extent permitted by law.
12
13 # resolve_file [file]
14 #
15 # If the argument is a symbolic link, print the target of that link.
16 # Otherwise, prints the basename of file.
17 resolve_file () {
18   test $# -eq 1 || return
19
20   # Ensure filename won't be confused for any kind of find argument...
21   case $1 in
22   /*) :;;
23   *) set x "./$1"; shift
24   esac
25
26   find "$1" -prune \( -type l -printf '%l' -o -printf '%f' \)
27 }
28
29 if [[ -z "$MUSIC" ]]; then
30         MUSIC=/home/music
31 fi
32
33 thumbs="$HOME/.fvwm/.thumbs"
34
35 if ! [[ -d "$thumbs" ]]; then
36         mkdir "$thumbs" || exit 1
37 fi
38
39 size="x128"
40 printimg=""
41 ismusic=""
42
43 while [[ "${1#--}" != "$1" && "$1" != "-" ]]; do
44         if   [[ "$1" == "--small" ]]; then
45                 size="56"
46         elif [[ "$1" == "--size"  ]]; then
47                 size="$2"
48                 shift
49         elif [[ "$1" = "--music"  ]]; then
50                 ismusic="yes"
51         elif [[ "$1" = "--image"  ]]; then
52                 printimg="yes"
53         else
54                 echo "unrecognised option: $1" 1>&2
55                 exit 1
56         fi
57         shift
58 done
59 [ "$1" = "-" ] && shift
60
61 if ! [[ "$size" =~ '^([0-9]*(x[0-9]+)?)$' ]]; then
62         echo "invalid size specification: $size" 1>&2
63         exit 1
64 fi
65
66 if [[ -z "$1" ]]; then
67         echo "usage: thumbnail.zsh [--small|--size <spec>] [--image] [--music] path" 1>&2
68         exit 1
69 fi
70
71 if [[ -n "$ismusic" ]]; then
72         imgpath="$MUSIC/$(dirname "${1#$MUSIC}")/cover.jpg"
73         [[ ! -f "$imgpath" ]] && imgpath="${imgpath%jpg}png"
74 else
75         imgpath="$1"
76 fi
77
78 [[ ! -f "$imgpath" ]] && exit 0
79 image=`resolve_file "$imgpath"`
80 case $image in
81 /*) :;;
82 *) image=`dirname $imgpath`/$image
83 esac
84 [[ ! -f "$image" ]] && exit 0
85
86 thumb="$thumbs/$(echo -n $image | md5sum - | cut -d ' ' -f 1)_$size.png"
87 if [[ -f "$thumb" ]]; then
88         mtime_s="$(stat -c %Y -- "$image")"
89         mtime_t="$(stat -c %Y -- "$thumb")"
90         if [ "$mtime_s" -gt "$mtime_t" ]; then
91                 convert -scale "$size" "$image" "$thumb"
92         fi
93 else
94         convert -scale "$size" "$image" "$thumb"
95 fi
96
97 echo "$thumb"
98 [ -n "$printimg" ] && echo "$image"
99 exit 0