#!/usr/bin/env fish

set err_ok 0
set err_bad_arg 1
set err_bad_run 2

set appdir
set dmg
set tmpdir

function rm_if -a name
	if test -d $name
		rm -rf "$name"
		and echo "removed dir $name"
	else if test -f $name
		rm -f  "$name"
		and echo "removed file $name"
	end

	return 0
end

function perish -a ret
	rm_if "$tmpdir"
	exit "$ret"
end

function err -a ret
	echo "error, dropping build"
	rm_if "$appdir"
	rm_if "$dmg"
	perish $ret
end

function :
	echo "$argv"
	echo
	eval "$argv" || err $err_bad_run
end

set icon_name_Tycho "resources/icons/pfhor-hand_1024@2x.svgz"

set name $argv[1]
set exe $argv[2]

if test ! $name
	echo "program name needed (available: Tycho)"
	err $err_bad_arg
end

if test ! $exe
	echo "full path to executable required (ex. '$_ $name ~/bin/maraiah-tycho')"
	err $err_bad_arg
end

set app $name.app

set srcdir $PWD/(string lower "$name")
set exedir (dirname "$exe")
set appdir $exedir/$app

set tmpdir (mktemp -d)
set diskdir $tmpdir/disk
set icondir $tmpdir/$name.iconset

set icon_name "icon_name_$name"
set icon_name $$icon_name
set icon $srcdir/$icon_name
set dmg $exedir/$name.dmg

: rm_if "$appdir"

: mkdir -p "$appdir/Contents/"{Frameworks,MacOS,Resources}

: cp "$exe" "$appdir/Contents/MacOS"
: cp "$srcdir/resources/Info.plist" "$appdir/Contents"

: mkdir -p "$icondir"

: rsvg-convert -w 16   -h 16   "$icon" -o "$icondir/icon_16x16.png"
: rsvg-convert -w 32   -h 32   "$icon" -o "$icondir/icon_32x32.png"
: rsvg-convert -w 64   -h 64   "$icon" -o "$icondir/icon_64x64.png"
: rsvg-convert -w 128  -h 128  "$icon" -o "$icondir/icon_128x128.png"
: rsvg-convert -w 256  -h 256  "$icon" -o "$icondir/icon_256x256.png"
: rsvg-convert -w 512  -h 512  "$icon" -o "$icondir/icon_512x512.png"
: rsvg-convert -w 1024 -h 1024 "$icon" -o "$icondir/icon_512x512@2x.png"

: cp "$icondir/icon_32x32.png"   "$icondir/icon_16x16@2x.png"
: cp "$icondir/icon_64x64.png"   "$icondir/icon_32x32@2x.png"
: cp "$icondir/icon_256x256.png" "$icondir/icon_128x128@2x.png"
: cp "$icondir/icon_512x512.png" "$icondir/icon_256x256@2x.png"

: iconutil -c icns -o "$appdir/Contents/Resources/$name.icns" "$icondir"

for lnk in (cat "$exedir"/build/maraiah-tycho-*/out/etc/link.txt)
	set lnk (dirname "$lnk")
	: cp -r "$lnk" "$appdir/Contents/Frameworks"
end

echo "success: bundle written to $appdir"

if test ! "$NO_DMG"
	echo "creating the disk image..."

	: rm_if "$dmg"

	: mkdir -p "$diskdir"
	: cp -r "$appdir" "$diskdir"
	: cp "$srcdir/resources/Image.DS_Store" "$diskdir/.DS_Store"
	: ln -s /Applications "$diskdir"
	: hdiutil create -volname "$name" -srcfolder "$diskdir" "$dmg"

	echo "success: dmg written to $dmg"
end

perish $err_ok

## EOF
