#!/bin/sh
#
#    Bundle AndroWish SDK from prepared source tree
#
############################################################################

die() {
    echo >&2 $1
    exit 1
}

# check prerequisites
test -d assets || die "assets directory missing"
test -d libs || die "libs directory missing"
test -d res || die "res directory missing"
test -d bin/classes || die "bin/classes directory missing, please rebuild"

# output directories
outer=/tmp/out$$
out=$outer/AWSDK

# populate output directory
mkdir -p $out
cp -rp res $out
mkdir $out/libs
cp -p libs/*.jar $out/libs
test -d libs/armeabi && \
    mkdir $out/libs/armeabi && \
    cp -p libs/armeabi/*.so $out/libs/armeabi
test -d libs/x86 && \
    mkdir $out/libs/x86 && \
    cp -p libs/x86/*.so $out/libs/x86
test -d libs/arm64-v8a && \
    mkdir $out/libs/arm64-v8a && \
    cp -p libs/arm64-v8a/*.so $out/libs/arm64-v8a
test -d libs/x86_64 && \
    mkdir $out/libs/x86_64 && \
    cp -p libs/x86_64/*.so $out/libs/x86_64
cp -rpL assets $out
cp -p sdktools/manifest.template $out/AndroidManifest.xml
cp -p sdktools/README.txt $out
cp -p ant.properties \
    build.properties \
    build.xml \
    default.properties \
    license.terms \
    proguard-project.txt \
    project.properties \
    $out
# gradle parts
cp -p sdktools/build.gradle \
    sdktools/gradlew \
    sdktools/gradlew.bat \
    sdktools/settings.gradle \
    $out
cp -rp sdktools/gradle $out

mkdir -p $out/assets/app
mkdir -p $out/tools
cp -p sdktools/bones $out/tools
cp -p sdktools/androwish.png $out/tools

# package tk.tcl.wish classes into androwish.jar except resources
(
    cd bin/classes
    zip -q -r $out/libs/androwish.jar * -x \
	tk/tcl/wish/R.class tk/tcl/wish/R\$\*.class \
	tk/tcl/wish/BuildConfig.class
)

# fixups in assets/androwish/bones et.al.
sed -i \
  -e 's@jni/sdl2tk/library/fonts@assets/sdl2tk*/fonts@g' \
  -e 's@jni/sdl2tk/library/demos@assets/sdl2tk*/demos@g' \
  -e 's@jni/tcl/library/tzdata@assets/tcl8*/tzdata@g' \
  $out/assets/INVENTORY
sed -i -e 's@name="AndroWish"@name="AndroWishApp"@g' $out/build.xml

# write source of Java class for app entry point
mkdir -p $out/src/your/packagename
cat > $out/src/your/packagename/YourClassName.java<<'EOD'
package your.packagename;
public class YourClassName extends tk.tcl.wish.AndroWish {
    /* empty class body */
}
EOD

# package everything in final SDK ZIP archive
(
    here=$(pwd)
    cd $outer
    rm -f "$here/AWSDK.zip"
    zip -q -r "$here/AWSDK.zip" AWSDK
)

# cleanup output directory
rm -rf $outer
