# Unzip curl
if [[ "$ARCH" = "arm" ]]; then
	unzip $MODPATH/bin/curl.zip -d $MODPATH/bin
elif [[ "$ARCH" = "arm64" ]]; then
	unzip $MODPATH/bin/curl64.zip -d $MODPATH/bin
else
	echo "Unsupported CPU Architecture"
	exit
fi
chmod 0755 $MODPATH/bin/$ARCH/curl

# Alias for Curl
alias curl='$MODPATH/bin/$ARCH/curl --dns-servers 1.1.1.1,1.0.0.1'

# Variables
local LOS=$(getprop | grep -o -c "lineage")
local Latest32=$(curl -s https://codeberg.org/AXP-OS/app_aosmium/releases | grep webview32-signed.apk | grep -m 1 -o https://codeberg.org/AXP-OS/app_aosmium/releases/download/.*.apk)
local Latest64=$(curl -s https://codeberg.org/AXP-OS/app_aosmium/releases | grep webview64-signed.apk | grep -m 1 -o https://codeberg.org/AXP-OS/app_aosmium/releases/download/.*.apk)

# API Check
if [[ $API -ge 28 ]]; then
	echo "Your Android Version is Supported!"
else
	abort "Your Android Version is not Supported!"
fi

# Custom ROM Check
if [[ $LOS -gt 0 ]]; then
	WVP=/system/product/app/AosmiumWebView
	echo "LineageOS Based Custom ROM Detected!"
else
	WVP=/system/app/AosmiumWebView
fi
mkdir -p "$MODPATH"/$WVP

# Download and Install WebView
echo "Download and Install Aosmium WebView..."
if [[ "$ARCH" = "arm" ]]; then
	curl -o $MODPATH/$WVP/AosmiumWebView.apk $Latest32
	su -c cp $MODPATH/$WVP/AosmiumWebView.apk /data/local/tmp
	su -c pm install --install-location 1 /data/local/tmp/AosmiumWebView.apk
	echo "Aosmium WebView Downloaded and Installed!"
elif [[ "$ARCH" = "arm64" ]]; then
	curl -o $MODPATH/$WVP/AosmiumWebView.apk $Latest64
	su -c cp $MODPATH/$WVP/AosmiumWebView.apk /data/local/tmp
	su -c pm install --install-location 1 /data/local/tmp/AosmiumWebView.apk
	echo "Aosmium WebView Downloaded and Installed!"
fi

# Check for Overlay Directory (code from OpenWebview)
echo "Checking for Overlay Directory..."
if [[ $LOS -gt 0 ]]; then
	OVERLAY_PATH=system/product/overlay/
	elif [[ -d /system_ext/overlay ]]; then
	OVERLAY_PATH=system/system_ext/overlay/
	elif [[ -d /system/overlay ]]; then
	OVERLAY_PATH=system/overlay/
	elif [[ -d /system/vendor/overlay ]]; then
	OVERLAY_PATH=system/vendor/overlay/
	echo "Overlay Directory Found!"
else
	echo "Unable to Find a Correct Overlay Path!"
fi

# Create Overlay Directory and Copy Overlay.apk
echo "Creating Overlay Directory Inside the Module..."
mkdir -p "$MODPATH"/$OVERLAY_PATH
if [[ $API -eq 28 ]]; then
	cp $MODPATH/Overlay/WebViewOverlay28.apk $MODPATH/$OVERLAY_PATH/WebViewOverlay.apk
elif [[ $API -ge 29 ]]; then
	cp $MODPATH/Overlay/WebViewOverlay29.apk $MODPATH/$OVERLAY_PATH/WebViewOverlay.apk
fi

# Some CleanUp
echo "Cleaning Up..."
mv $MODPATH/bin/$ARCH/curl $MODPATH/bin/curl
rm -rf $MODPATH/bin/$ARCH
rm -rf $MODPATH/bin/*.zip
rm -rf $MODPATH/system/.placeholder
rm -rf $MODPATH/Overlay
rm -rf $MODPATH/common
