#!/bin/bash

# this script assumes that in
# ~/bromite  ---> there is the bromite repo
# ~/chromium ---> there is the chromium repo

RED='\033[0;31m'
NC='\033[0m' # No Color

cd ~

echo -e ${RED} -------- download bromite repo ${NC}
mkdir ~/bromite
cd ~/bromite
git fetch
git pull

VERSION=$( cat ~/bromite/build/RELEASE )
echo -e ${RED} -------- lastest version is: $VERSION ${NC}


echo -e ${RED} -------- download chromium repo ${NC}
mkdir ~/chromium
cd ~/chromium
#fetch --nohooks --no-history android

gclient config https://chromium.googlesource.com/chromium/src.git
echo "target_os=['android']" >>.gclient

cd src

# cleanup repo!
#git reset
#git reset --hard HEAD
#git clean -fdx
git fetch --depth 2 https://chromium.googlesource.com/chromium/src.git +refs/tags/$VERSION:chromium_$VERSION
#git tag
#git checkout .
#git clean -fdx
#git am --abort && git reset 95a0064cd30fa82247881080e7f70d9904c79864^ && git reset --hard && git clean -f -d 
git checkout $VERSION

echo -e ${RED} -------- git current status ${NC}
git status
git log

echo -e ${RED} -------- sync other chromium repos ${NC}
gclient sync -D --no-history

# remove origin for chromium
git remote remove origin

echo -e ${RED} ------- apply patchs ${NC}
for file in $(cat ~/bromite/build/bromite_patches_list.txt) ; do 
	echo -e ${RED} " -> Apply $file" ${NC}

	REPL="0,/^---/s//FILE:"$file"\n---/"
	cat ~/bromite/build/patches/$file  | sed $REPL | git am
	
	if [ $? -ne 0 ]
	then
        echo -e "Error on ~/bromite/build/patches/${file} press return"

        read -n 1
	fi

	echo " "
done

file="Add-a-flag-to-always-view-desktop-site-for-all-websites.patch"
REPL="0,/^---/s//FILE:"$file"\n---/"
cat ~/bromite/build/patches/$file  | sed $REPL | git am


	
# install builds deps
sudo build/install-build-deps-android.sh
gclient runhooks

# generate ninja files and autogenerated files
gn gen --args="$(cat ~/bromite/build/GN_ARGS) target_cpu=\"arm64\" " out/arm64

# build time!
set NINJA_SUMMARIZE_BUILD=1
date && autoninja -C out/arm64 chrome_public_apk && date && adb install out/arm64/apks/ChromePublic.apk




PATH=/root/chromium/src/third_party/llvm-build/Release+Asserts/bin:/root/depot_tools/:$PATH

ccache --max-size=10G
export CCACHE_CPP2=yes
export CCACHE_SLOPPINESS=time_macros
gn gen --args="$(cat ~/bromite/build/GN_ARGS) target_cpu=\"arm64\" cc_wrapper=\"ccache\" " out/arm64
