#!/bin/bash

# package-stamps.sh
#
# Pere Pujal i Carabantes <pere@provant.freeddns.org>
# Minor edits Bill Kendrick <bill@newbreedsoftware.com>
# Last updated: 2020-06-08
#
# This script takes the Tux Paint stamps and packages them
# into pieces (based on stamp category, as well as language
# for the spoken descriptive audio files).
#
# The resulting files are to be hosted somewhere that is
# accessible to a simple add-on app for Android, which allows
# end users to only download and install the stamps/languages
# that they want.


# Abort on errors!
set -e

# Check for proper usage
if [ "a$1b" = "ab" -o "a$2b" = "ab" ]; then
  echo "Usage $0 builddir xmlname.xml"
  echo
  echo " * 'builddir' is the destination where the collected stamp files"
  echo "   are to be copied and packaged."
  echo "   (Please use an empty dir, there are some rm -rf called there)"
  echo " * 'xmlname.xml' is the name of the xml file to be created that will "
  echo "   contain the interface for the Android stamps downloader."
  echo
  echo "Typical example usage:"
  echo "  cd path/to/tuxpaint-stamps/android"
  echo "  $0 YYYY-MM-DD YYYY-MM-DD.xml"
  echo "  mv YYYY-MM-DD.xml app/src/main/res/layout/stampstree.xml"
  echo "  mv filelist-YYYY-MM-DD.xml app/src/main/res/values/filelist_stampstree.xml"
  echo
  echo "  publish the generated .zip files somewhere"
  echo "  edit the default server path in app/src/main/res/layout/downloadstamps.xml"
  echo "  to point to the URL were the zip files are hosted,"
  echo "  the 'android:text=\"https://....' line just under 'texturl'"
  echo
  echo "  build the android downloader with"
  echo "  'gradle build', you'll need recent versions of gradle and android sdk"
  echo "  then sign the generated apk in app/build/outputs/apk/release/ and publish it."
  echo
  exit 1
fi


# Locations of things (relative to "android" subdir)

STAMPDIR="../stamps/"
PODIR="../po/"


# Gather list of stamp category directories

DIRS=`ls ${STAMPDIR}`


spacing=0
increasing=20

spacing=$(( $spacing + $increasing ))

# Begin the XML file

echo "Recording XML into $2"
echo

echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<!-- DO NOT EDIT THIS FILE, IT WILL BE AUTOGENERATED EACH NEW STAMPS RELEASE AND YOUR CHANGES ERASED -->
<!-- IF YOU WANT TO MAKE CHANGES IN THIS FILE, PLEASE MODIFY THE SCRIPT THAT GENERATES IT, IN THE TUXPAINT-STAMPS PACKAGE -->

    <LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"
        android:layout_width=\"fill_parent\"
        android:layout_height=\"wrap_content\"
        android:orientation=\"vertical\" >

        <LinearLayout 
            android:layout_width=\"fill_parent\"
            android:layout_height=\"wrap_content\"
            android:orientation=\"horizontal\" >

            <Button
                android:id=\"@+id/Button_stamps\"
                android:background=\"@drawable/down\"
                android:onClick=\"button_clicked\"
                android:tag=\"Button_stamps\"
                android:layout_marginLeft=\""$spacing"dp\"
                android:layout_marginStart=\""$spacing"dp\"
                android:layout_width=\"wrap_content\"
                android:layout_height=\"wrap_content\"  />
            <CheckBox
                android:id=\"@+id/checkBox_stamps\"
                android:layout_width=\"fill_parent\"
                android:layout_height=\"wrap_content\"
                android:tag=\"checkBox_stamps\"
                android:enabled=\"true\"
		android:checked=\"true\"
                android:onClick=\"checkbox_clicked\"
                android:text=\"@string/all_stamps\"
                android:visibility=\"visible\"
                android:longClickable=\"true\" />

        </LinearLayout>
" > $2

echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>" > filelist_$2
echo "<resources>" >> filelist_$2

echo "<string-array name=\"categories\">" >> filelist_$2

for dir in $DIRS; do 
    echo "<item>$dir</item>" >> filelist_$2
done
echo "</string-array>" >> filelist_$2

# Storing a list of checkboxes in $2.tmp
echo -n "android:tag=\"" > $2.tmp
  
spacing=$(( $spacing + $increasing ))


echo
echo "## Scanning for images and sound effects ##"

# Traverse the stamp categories / directories:

for dir in $DIRS; do
  echo -n -e "Scan for images and sound effects for $dir ...\t"

  # Grab all of the stamp imagery (.png & .svg),
  # settings (.dat), descriptive text (.txt), and
  # sound effects (.ogg & .wav),
  # but NOT the spoken descriptive sounds (*_desc*.wav & *_desc*.ogg) 
  find ${STAMPDIR}$dir \
    \( \
      \( -name *.png -o -name *.svg -o -name *.txt -o -name *.dat -o -name *.ogg -o -name *.wav \) \
      ! -name *_desc*.ogg \
      ! -name *_desc*.wav \
    \) \
    -printf "install -D %p $1/stamps/$dir/%P\n" \
    | sort \
    | sh

  # ZIP the dir, change to $1 directory to avoid have its path inside the zip
    cd $1 && \
    zip -qr tuxpaint-stamps-$dir-$1.zip stamps && \
    cd .. && \
    SIZE=`stat -c %s $1/tuxpaint-stamps-$dir-$1.zip` && \
    echo "Packaged into $1/tuxpaint-stamps-$dir-$1.zip"

  # Clean up
  rm -rf $1/stamps && \

  # Add a checkbox to the XML for this package
  echo "
        <CheckBox
            android:id=\"@+id/checkBox_stamps_"$dir"\"
            android:layout_width=\"fill_parent\"
            android:layout_height=\"wrap_content\"
            android:tag=\"checkBox_stamps_"$dir" parent checkBox_stamps /parent kind stamps /kind category "$dir" /category size "$SIZE" /size zipfile tuxpaint-stamps-"$dir-$1".zip /zipfile\"
            android:enabled=\"true\"
            android:onClick=\"checkbox_clicked\"
            android:text=\"@string/"$dir"\"
            android:visibility=\"gone\" 
            android:layout_marginLeft=\""$spacing"dp\"
            android:layout_marginStart=\""$spacing"dp\"
            android:longClickable=\"true\" />

" >> $2

  # Track it in the file list
  echo "<string-array name=\"tuxpaint_stamps_"$dir"\">" >> filelist_$2

  unzip -l $1/tuxpaint-stamps-$dir-$1.zip | grep "\." | grep -v Archive | sort -k 4 | while read filename; do
    echo "<item>$filename</item>" | sed "s/ .* / /g" >> filelist_$2
  done

  echo "</string-array>" >> filelist_$2

  # Track it in the temp file
  echo -n "checkBox_stamps_"$dir" ">> $2.tmp

done


spacing=$(( $spacing - $increasing ))

echo "
        <LinearLayout 
            android:layout_width=\"fill_parent\"
            android:layout_height=\"wrap_content\"
            android:orientation=\"horizontal\" >

            <TextView
                android:id=\"@+id/TextViewDescriptiveSounds\"
                android:text=\"@string/descriptive_sounds\"
                android:layout_marginLeft=\""$spacing"dp\"
                android:layout_marginStart=\""$spacing"dp\"
                android:layout_width=\"wrap_content\"
                android:layout_height=\"wrap_content\"  />

        </LinearLayout>

" >> $2


spacing=$(( $spacing + $increasing ))


echo
echo "## Scanning for sound descriptions ##"

wholelang="tobedone"
echo "English..."

for dir in $DIRS; do
  count=0

  for desc in `find ${STAMPDIR}$dir -name *desc.* -printf "%P\n" | sort`; do
    if [ "a${desc}b" != "ab" ]; then
      count=1
      install -D ${STAMPDIR}$dir/$desc $1/stamps/$dir/$desc
    fi
  done

  if [ $count -gt 0 ]; then
    echo -n -e "Sound descriptions found for English and category $dir ...\t"

    # ZIP the dir, change to $1 directory to avoid have its path inside the zip
    cd $1 && \
    zip -qr tuxpaint-stamps-desc-sounds-$dir-english-$1.zip stamps && \
    cd .. && \
    SIZE=`stat -c %s $1/tuxpaint-stamps-desc-sounds-$dir-english-$1.zip` && \
    echo "Packaged into $1/tuxpaint-stamps-desc-sounds-$dir-english-$1.zip."

    # Clean up
    rm -rf $1/stamps

    if [ $wholelang != "done" ]; then
      echo "
        <LinearLayout 
            android:layout_width=\"fill_parent\"
            android:layout_height=\"wrap_content\"
            android:orientation=\"horizontal\" >

            <Button
                android:id=\"@+id/Button_English\"
                android:tag=\"Button_English\"
                android:background=\"@drawable/down\"
                android:onClick=\"button_clicked\"
                android:layout_marginLeft=\""$spacing"dp\"
                android:layout_marginStart=\""$spacing"dp\"
                android:layout_width=\"wrap_content\"
                android:layout_height=\"wrap_content\"  />


            <CheckBox
                android:id=\"@+id/checkBox_English\"
                android:layout_width=\"fill_parent\"
                android:layout_height=\"wrap_content\"
                android:tag=\"checkBox_English\"
                android:enabled=\"true\"
                android:onClick=\"checkbox_clicked\"
                android:text=\"@string/english\"
                android:visibility=\"visible\" 
                android:longClickable=\"true\" />

        </LinearLayout>

" >> $2

      spacing=$(( $spacing + $increasing ))
      wholelang="done"
    fi

    echo "
        <CheckBox
            android:id=\"@+id/checkBox_English_"$dir"\"
            android:layout_width=\"fill_parent\"
            android:layout_height=\"wrap_content\"
            android:tag=\"checkBox_English_"$dir" parent checkBox_English /parent kind sounddescs /kind category "$dir" /category size "$SIZE" /size zipfile tuxpaint-stamps-desc-sounds-$dir-english-$1.zip /zipfile\"
            android:enabled=\"true\"
            android:onClick=\"checkbox_clicked\"
            android:text=\"@string/"$dir"\"
            android:visibility=\"gone\" 
            android:layout_marginLeft=\""$spacing"dp\"
            android:layout_marginStart=\""$spacing"dp\"
            android:longClickable=\"true\" />

" >> $2

    echo -n "checkBox_English_"$dir" ">> $2.tmp

    echo "<string-array name=\"tuxpaint_stamps_desc_sounds_"$dir"_english\">" >> filelist_$2

    unzip -l $1/tuxpaint-stamps-desc-sounds-$dir-english-$1.zip | grep "\." | grep -v Archive | sort -k 4 | while read filename; do
      echo "<item>$filename</item>" | sed "s/ .* / /g" >> filelist_$2
    done

    echo "</string-array>
" >> filelist_$2

  fi

done

spacing=$(( $spacing - $increasing ))


for language in `ls ${PODIR}*.po | sort`; do
  language=`echo $language | sed "s#${PODIR}##"`

  LL=`echo $language | sed "s#tuxpaint-stamps-##g" | sed "s/\.po//g"`

  # "@" not allowed in android:id, so ca@valencia and sr@latin to ca_valencia and sr_latin
  LL_=`echo $LL | sed "s/@/_/g"`

  echo
  echo "${LL}..."

  wholelang="tobedone"
  spacing=$(( $spacing + $increasing ))

  for dir in $DIRS; do
    count=0
    # Scan for existing sound descriptions
    for desc in `find ${STAMPDIR}$dir -name "*desc_${LL}.*" -printf "%P\n" | sort`; do
      if [ "a${desc}b" != "ab" ]; then
        count=$(( $count + 1 ))
        install -D ${STAMPDIR}$dir/$desc $1/stamps/$dir/$desc
      fi
    done

    if [ $count -gt 0 ]; then
      echo -e -n "Sound descriptions found for language $LL and category $dir ($count) ...\t"

      # ZIP the dir, change to $1 directory to avoid have its path inside the zip
      cd $1 && \
      zip -qr tuxpaint-stamps-desc-sounds-$dir-${LL_}-$1.zip stamps && \
      cd .. && \
      SIZE=`stat -c %s $1/tuxpaint-stamps-desc-sounds-$dir-${LL_}-$1.zip` && \
      echo "Packaged into $1/tuxpaint-stamps-desc-sounds-$dir-${LL_}-$1.zip."

      # Clean up
      rm -rf $1/stamps

      if [ $wholelang != "done" ]; then
        spacing=$(( $spacing - $increasing ))

        echo "
        <LinearLayout 
            android:layout_width=\"fill_parent\"
            android:layout_height=\"wrap_content\"
            android:orientation=\"horizontal\" >

            <Button
                android:id=\"@+id/Button_"$LL_"\"
                android:tag=\"Button_"$LL_"\"
                android:background=\"@drawable/down\"
                android:onClick=\"button_clicked\"
                android:layout_marginLeft=\""$spacing"dp\"
                android:layout_marginStart=\""$spacing"dp\"
                android:layout_width=\"wrap_content\"
                android:layout_height=\"wrap_content\"  />

            <CheckBox
                android:id=\"@+id/checkBox_"$LL_"\"
                android:layout_width=\"fill_parent\"
                android:layout_height=\"wrap_content\"
                android:tag=\"checkBox_"$LL_"\"
                android:enabled=\"true\"
                android:onClick=\"checkbox_clicked\"
                android:text=\"@string/"$LL"\"
                android:visibility=\"visible\" 
                android:longClickable=\"true\" />

        </LinearLayout>

" >> $2

        spacing=$(( $spacing + $increasing ))
        wholelang="done"
      fi

      echo "
            <CheckBox
                android:id=\"@+id/checkBox_"$LL_"_"$dir"\"
                android:layout_width=\"fill_parent\"
                android:layout_height=\"wrap_content\"
                android:tag=\"checkBox_"$LL_"_"$dir" parent checkBox_"$LL_" /parent kind sounddescs /kind category "$dir" /category size "$SIZE" /size zipfile tuxpaint-stamps-desc-sounds-$dir-$LL-$1.zip /zipfile\"
                android:enabled=\"true\"
                android:onClick=\"checkbox_clicked\"
                android:text=\"@string/"$dir"\"
                android:visibility=\"gone\" 
                android:layout_marginLeft=\""$spacing"dp\"
                android:layout_marginStart=\""$spacing"dp\"
                android:longClickable=\"true\" />

" >> $2

      echo -n "checkBox_"$LL_"_"$dir" ">> $2.tmp

      echo "<string-array name=\"tuxpaint_stamps_desc_sounds_"$dir"_"$LL_"\">" >> filelist_$2

      unzip -l $1/tuxpaint-stamps-desc-sounds-$dir-$LL_-$1.zip | grep "\." | grep -v Archive | sort -k 4 | while read filename; do
        echo "<item>$filename</item>" | sed "s/ .* / /g" >> filelist_$2
      done

      echo "</string-array>
" >> filelist_$2

    else
      echo "No sound descriptions found for language $LL and category $dir found"
    fi

  done
  spacing=$(( $spacing - $increasing ))
done
spacing=$(( $spacing - $increasing ))

echo "            <Button
                android:id=\"@+id/Button_list\"
                android:onClick=\"button_clicked\"
                android:visibility=\"gone\"
                android:layout_width=\"wrap_content\"
                android:layout_height=\"wrap_content\" " >> $2

cat $2 $2.tmp > $2.tmp.tmp
mv $2.tmp.tmp $2
rm $2.tmp

echo "\" />
    </LinearLayout>
" >> $2

echo "</resources>
" >> filelist_$2


# Test the XML files for valid formatting
xmllint --noout $2
xmllint --noout filelist_$2

echo
echo "Done"

