#!/bin/bash
. bean_func.fnc

BR="
"

# 引数が無ければドロップ窓を出す
if [ $# -gt 0 ] ; then
	for i in "$@" ; do
		filelist="${filelist}${BR}${i}"
	done
	filelist=$(echo "${filelist}" | tail -n +2)
else
	filelist=$(yad --title="画像を一括で拡大／縮小" \
	--window-icon=imagemagick --image=imagemagick \
	--borders=10 --on-top --center --dnd \
	--text "このウインドウに画像をドロップした後、OKを押してください。\n\n（※LiveCD環境では、デスクトップに保存された画像が\n再読み込みしない限り表示されません。）")
	
	if [ $? -gt 0 ] ; then
		exit 1
	fi
	
	filelist=$(Bean_PathConv "${filelist}" | sort | uniq)
fi

if [ "${filelist}" == "" ] ; then
	exit 1
fi

desktop=`Bean_UserDirs DESKTOP`

input=`yad --title "画像を一括で拡大／縮小" \
--window-icon=imagemagick --on-top --center --form \
--field="形式:CB"   'JPEG!PNG' \
--field="圧縮率:CB" '90!95!100!85!80!75!70!65!60' \
--field="大きさ:CB" 'ピクセル指定!パーセント指定' \
--field="縦横比:CB" '枠に収める!無視して変形' \
--field="縦:NUM" \
--field="横:NUM"`

if [ "$input" == "" ] ; then
	exit 1
fi

x=`echo $input | awk -F'\|' '{print $6}' | sed -e 's/\.[0-9]*$//'`
y=`echo $input | awk -F'\|' '{print $5}' | sed -e 's/\.[0-9]*$//'`

if [ "$x" == "0" ] ; then
	yad --title "エラー" --text "サイズを0にはできません" \
	--window-icon=imagemagick --image=application-exit --on-top --center
	exit 1
fi

if [ "$y" == "0" ] ; then
	yad --title "エラー" --text "サイズを0にはできません" \
	--window-icon=imagemagick --image=application-exit --on-top --center
	exit 1
fi

if [ "`echo $input | awk -F'\|' '{print $1}'`" == "JPEG" ] ; then
	f="jpg"
	q="-quality"
	qp=`echo $input | awk -F'\|' '{print $2}'`
else
	f="png"
	q=""
fi

if [ "`echo $input | awk -F'\|' '{print $3}'`" == "ピクセル指定" ] ; then
	p=""
	pf=""
else
	p="%"
	pf="PC"
fi

if [ "`echo $input | awk -F'\|' '{print $4}'`" == "枠に収める" ] ; then
	e=""
else
	e="!"
fi


echo $x x $y
echo $f $q
echo $p $pf $e


# 区切り文字を改行に
_IFS="$IFS";IFS="${BR}"

# リストを順番に処理
for i in $filelist ; do
	j=`Bean_PathConv "$i"`
	k=${desktop}/`Bean_NoExt $(basename "$j")`_${x}${pf}x${y}${pf}.${f}
	convert ${q} ${qp} -resize ${x}${p}x${y}${p}${e} "${j}" "${k}"
done

# 区切り文字を戻す
IFS="$_IFS"
