#!/bin/bash
# cannot `set -e` due to missing non-critical files


# this is `build-retroarch-android.sh` version 2019-0813-1943
# https://ocv.me/dev/?gist/build-retroarch-android.sh
#
# USAGE:
# make a clean checkout of https://github.com/libretro/libretro-super/tree/053769bf82eff1cd601b4f24d58cb414f7d9c511
# and copy me into the root since i depend on dist/info/*.info  (core descriptions)
#
# see line 280 onwards to create a debian chroot for this


# from https://github.com/libretro/libretro-super/blob/053769bf82eff1cd601b4f24d58cb414f7d9c511/recipes/android/retroarch-android.conf
# 
cat >/dev/null <<EOF
ANDROID_HOME /home/buildbot/tools/android/android-sdk-linux
PATH /home/buildbot/tools/android/android-sdk-linux/tools/bin
PLATFORM android
platform android
MAKE make
RA YES
LIBSUFFIX _android
EOF
# end of libretro-super snip

# adjusted for debootstrap amd64 sid 2019-0813 with depends:
#   part1: openjdk-8-jdk-headless git pixz file libncurses5
#   part2: ant
#
export ANDROID_HOME=/usr/lib/android-sdk
export NDK_ROOT_DIR=/usr/lib/android-ndk
export PLATFORM=android
export platform=android
export MAKE=make
export RA=YES
export LIBSUFFIX=_android

export PATH="$ANDROID_HOME:$NDK_ROOT_DIR:$PATH"
export WORK="$(pwd)"
export BASE_DIR=$(dirname "$0")
export RARCH_DIR="$BASE_DIR/dist"
export RARCH_DIST_DIR="$RARCH_DIR/$DIST_DIR"
export RECIPE="/dev/shm/retroarch-android"
export PKG_EXTRA=
export BUILD=YES

# from https://github.com/libretro/libretro-super/blob/053769bf82eff1cd601b4f24d58cb414f7d9c511/recipes/android/retroarch-android.ra
# 
cat >$RECIPE.ra <<'EOF'
retroarch retroarch https://github.com/libretro/Retroarch.git PROJECT YES .
overlays overlays https://github.com/libretro/common-overlays.git ASSETS YES retroarch/media
shaders shaders_glsl https://github.com/libretro/glsl-shaders.git ASSETS YES retroarch/media
autoconfig autoconfig https://github.com/libretro/retroarch-joypad-autoconfig.git ASSETS YES retroarch/media
assets assets https://github.com/libretro/retroarch-assets.git ASSETS YES retroarch/media
libretrodb libretrodb https://github.com/libretro/libretro-database.git ASSETS YES retroarch/media
EOF
# end of libretro-super snip

# mocks
#
buildbot_handle_message() { echo duly noted; }
buildbot_log() { echo duly noted; }

# from https://github.com/libretro/libretro-super/blob/053769bf82eff1cd601b4f24d58cb414f7d9c511/libretro-buildbot-recipe.sh#L758-839
#
buildbot_pull(){
	[ -f "$RECIPE.ra" ] || return 0

	while read line; do
		eval "set -- \$line"

		NAME="$1"
		DIR="$2"
		URL="$3"
		TYPE="$4"
		ENABLED="$5"
		PARENTDIR="$6"
		ARGS=""

		shift 6
		while [ $# -gt 0 ]; do
			ARGS="${ARGS} ${1}"
			shift
		done

		ARGS="${ARGS# }"
		ARGS="${ARGS%"${ARGS##*[![:space:]]}"}"

		if [ "${ENABLED}" = "YES" ] && [ "${TYPE}" = "PROJECT" ] || [ "${TRAVIS:-0}" = "0" ]; then
			echo "buildbot job: $jobid Processing $NAME"
			echo
			echo "NAME: $NAME"
			echo "DIR: $DIR"
			echo "PARENT: $PARENTDIR"
			echo "URL: $URL"
			echo "REPO TYPE: $TYPE"
			echo "ENABLED: $ENABLED"

			if [ -d "${PARENTDIR}/${DIR}/.git" ]; then
				cd $PARENTDIR
				cd $DIR

				if [ -f .forcebuild ]; then
					echo "found .forcebuild file, building $NAME"
					BUILD="YES"
				fi

				echo "pulling changes from repo $URL... "
				HEAD="$(git rev-parse HEAD)"
				git pull

				if [ "${TYPE}" = "PROJECT" ]; then
					RADIR=$DIR
					if [ "$HEAD" = "$(git rev-parse HEAD)" ] && [ "${BUILD}" != "YES" ]; then
						BUILD="NO"
					else
						echo "resetting repo state $URL... "
						git reset --hard FETCH_HEAD
						git clean -xdf
						BUILD="YES"
					fi
				fi
				cd $WORK
			else
				echo "cloning repo $URL..."
				cd $PARENTDIR
				if [ "${BRANCH}" ] && [ "${NAME}" = "retroarch" ]; then
					git clone "$URL" "$DIR"
					cd $DIR
					git checkout "$BRANCH"
				else
					git clone -b "${GIT_BRANCH:-master}" "$URL" "$DIR" --depth=1
				fi
				cd $WORK
				if [ "${TYPE}" = "PROJECT" ]; then
					BUILD="YES"
					RADIR=$DIR
				fi
				cd $WORK
			fi
			echo
			echo "RADIR=$RADIR"
		fi

	done < $RECIPE.ra
	cd $WORK
}
# end of libretro-super snip


buildit() {
# from https://github.com/libretro/libretro-super/blob/053769bf82eff1cd601b4f24d58cb414f7d9c511/libretro-buildbot-recipe.sh#L980-1080
#
if [ "${PLATFORM}" = "android" ] && [ "${RA}" = "YES" ]; then

	if [ "${BUILD}" = "YES" -o "${FORCE}" = "YES" -o "${FORCE_RETROARCH_BUILD}" == "YES" ]; then

		#${HELPER} ${MAKE} -f Makefile.griffin shaders-convert-glsl PYTHON3=$PYTHON

		echo "buildbot job: $jobid processing assets"
		echo

		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/assets
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/cores
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/info
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/overlays
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/shaders/shaders_glsl/
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/shaders/shaders_slang/
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/database
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/autoconfig
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/cheats
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/playlists
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/dowloads
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/remaps
		rm -rf pkg/android/phoenix$PKG_EXTRA/assets/system

		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/assets
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/assets/xmb/monochrome
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/assets/ozone
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/cores
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/info
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/overlays
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/shaders/shaders_glsl
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/shaders/shaders_slang
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/database/cursors
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/database/rdb
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/autoconfig
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/cheats
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/playlists
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/dowloads
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/remaps
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/saves/
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/states/
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/system/
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/filters/video
		mkdir -p pkg/android/phoenix$PKG_EXTRA/assets/filters/audio

		# Copy over fonts manually
		cp -rf media/assets/ozone/bold.ttf pkg/android/phoenix$PKG_EXTRA/assets/assets/ozone
		cp -rf media/assets/ozone/regular.ttf pkg/android/phoenix$PKG_EXTRA/assets/assets/ozone

		cp -rf media/assets/glui pkg/android/phoenix$PKG_EXTRA/assets/assets/
		cp -rf media/assets/xmb/monochrome pkg/android/phoenix$PKG_EXTRA/assets/assets/xmb
		cp -rf media/assets/ozone/png pkg/android/phoenix$PKG_EXTRA/assets/assets/ozone

		cp -rf media/assets/menu_widgets pkg/android/phoenix$PKG_EXTRA/assets/assets/
		cp -rf media/assets/s* pkg/android/phoenix$PKG_EXTRA/assets/assets/
		cp -rf media/autoconfig/* pkg/android/phoenix$PKG_EXTRA/assets/autoconfig/
		cp -rf media/overlays/* pkg/android/phoenix$PKG_EXTRA/assets/overlays/
		cp -rf media/shaders_glsl/* pkg/android/phoenix$PKG_EXTRA/assets/shaders/shaders_glsl/
		cp -rf media/shaders_slang/* pkg/android/phoenix$PKG_EXTRA/assets/shaders/shaders_slang/
		cp -rf media/libretrodb/cursors/* pkg/android/phoenix$PKG_EXTRA/assets/database/cursors/
		cp -rf media/libretrodb/rdb/* pkg/android/phoenix$PKG_EXTRA/assets/database/rdb/
		cp -rf libretro-common/audio/dsp_filters/*.dsp pkg/android/phoenix$PKG_EXTRA/assets/filters/audio/
		cp -rf gfx/video_filters/*.filt pkg/android/phoenix$PKG_EXTRA/assets/filters/video/
		find pkg/android/phoenix$PKG_EXTRA/assets/assets/ -type d -name src -exec rm -rf {} \;


		#cp -rf media/shaders_glsl $TMPDIR/
		touch pkg/android/phoenix$PKG_EXTRA/assets/cheats/.empty-folder
		touch pkg/android/phoenix$PKG_EXTRA/assets/saves/.empty-folder
		touch pkg/android/phoenix$PKG_EXTRA/assets/states/.empty-folder
		touch pkg/android/phoenix$PKG_EXTRA/assets/system/.empty-folder

		cp -rf $RARCH_DIR/info/* pkg/android/phoenix$PKG_EXTRA/assets/info/

		echo "buildbot job: $jobid Building"
		echo
		cd pkg/android/phoenix$PKG_EXTRA

		git reset --hard
		if [ "${RELEASE}" == "NO" ]; then
			python ./version_increment.py
		fi
		./gradlew clean assembleRelease | tee -a "$LOGFILE"
		cp -r build/outputs/apk/normal/release/phoenix-normal-release.apk $RARCH_DIR/retroarch-release.apk | tee -a "$LOGFILE"
		cp -r build/outputs/apk/normal/release/phoenix-normal-release.apk $RARCH_DIR/retroarch-release.apk
		cp -r build/outputs/apk/aarch64/release/phoenix-aarch64-release.apk $RARCH_DIR/retroarch-aarch64-release.apk | tee -a "$LOGFILE"
		cp -r build/outputs/apk/aarch64/release/phoenix-aarch64-release.apk $RARCH_DIR/retroarch-aarch64-release.apk
		cp -r build/outputs/apk/ra32/release/phoenix-ra32-release.apk $RARCH_DIR/retroarch-ra32-release.apk | tee -a "$LOGFILE"
		cp -r build/outputs/apk/ra32/release/phoenix-ra32-release.apk $RARCH_DIR/retroarch-ra32-release.apk

		RET=$?
		buildbot_handle_message "$RET" "$ENTRY_ID" "retroarch" "$jobid" "$LOGFILE"

		if [ $RET -eq 0 ]; then
			touch $TMPDIR/built-frontend
		fi

		ENTRY_ID=""
	fi
fi
# end of libretro-super snip

}

[ "$1" = "pull" ]  && { buildbot_pull; exit $?; }
[ "$1" = "build" ] && { cd retroarch && git submodule update --init && buildit; exit $?; }

echo 'need arg 1: pull or build'
exit 1



########################################################################
########################################################################
#
#   EOF: retroarch android app build (sans cores)
#
########################################################################
########################################################################



# quick debian chroot howto;
# tested on alpine but should run anywhere
#

vchroot() { mount | awk '/^[^ ]+ on \/c\/deb64-sid\// {print $3}'; }

unch() {
  cd
  while [ ! -z "$(vchroot | tee /dev/stderr)" ]; do
    vchroot | xargs umount; sleep 0.5; done
  
  echo ==
  mount | grep deb64-sid && return 1
  lsof / 2>/dev/null | grep deb64-sid && return 1
  return 0
}

ench() {
  xhost local:root
  iptables -I OUTPUT 1 -m owner --uid-owner 1984 -j DROP
  cat /var/lib/dbus/machine-id > /c/deb64-sid/var/lib/dbus/machine-id
  sudo -u ed pactl load-module module-native-protocol-unix auth-anonymous=1 socket=/tmp/pulse-socket
  mount | grep ' on /c/deb64-sid/tmp '     || mount --bind /tmp     /c/deb64-sid/tmp
  mount | grep ' on /c/deb64-sid/proc '    || mount --bind /proc    /c/deb64-sid/proc
}

ench_inst() {
  ench
  mount | grep ' on /c/deb64-sid/dev '     || mount --bind /dev     /c/deb64-sid/dev
  mount | grep ' on /c/deb64-sid/dev/pts ' || mount --bind /dev/pts /c/deb64-sid/dev/pts
  mount | grep ' on /c/deb64-sid/dev/shm ' || mount --bind /dev/shm /c/deb64-sid/dev/shm
}

mkdir /var/cache/debootstrap; debootstrap --force-check-gpg --arch=amd64 --cache-dir=/var/cache/debootstrap sid /c/deb64-sid https://ftp.acc.umu.se/debian/

ench_inst; TERM=xterm chroot /c/deb64-sid <<'EOF'
useradd -m -p k -s /bin/bash -u 1000 ned
echo "deb https://ftp.acc.umu.se/debian sid main contrib non-free" > /etc/apt/sources.list
apt update
apt -y dist-upgrade
apt -y install openjdk-8-jdk-headless git pixz file libncurses5
apt -y install ant

find /var/cache/apt/archives -name '*.deb' -delete
rm /var/cache/apt/* || true
rm /var/lib/apt/lists/*debian_dists_sid*
EOF

unch && cd /c && tar -c deb64-sid/ | pixz -7k > zips/deb64-sid-jdk8.tpxz; ll zips

ench_inst; TERM=xterm chroot /c/deb64-sid <<'EOF'
mkdir -p /usr/lib/android-sdk/ &&
cd /usr/lib/android-sdk/ &&
wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip &&
echo "92ffee5a1d98d856634e8b71132e8a95d96c83a63fde1099be3d86df3106def9  sdk-tools-linux-4333796.zip" |
sha256sum -c || { echo dl error; exit 1; }

yes | /usr/lib/android-sdk/tools/bin/sdkmanager --install "build-tools;28.0.3" "platforms;android-28" "patcher;v4" "ndk-bundle"
EOF

unch && cd /c && tar -c deb64-sid/ | pixz -7k > zips/deb64-sid-jdk8-android.tpxz; ll zips
