#!/usr/bin/env sh

. $PWD/app.conf

DEFAULT_APP_ID="de.anyschool.app"
DEFAULT_CONFIG_MODE="WEB"

APP_ID="${APP_ID:-$DEFAULT_APP_ID}"
APP_VERSION=$(jq '.version' app/package.json)
CONFIG_MODE="${CONFIG_MODE:-$DEFAULT_CONFIG_MODE}"

if [ "$CONFIG_MODE" = 'ANDROID' ]; then
  APP_ID="$ANDROID_PACKAGE_NAME"
fi

if [ "$CONFIG_MODE" = 'IOS' ]; then
  APP_ID="$IOS_BUNDLE_IDENTIFIER"
fi

# ionic config
cat app/ionic.config.json | jq '.name = $newName' --arg newName "$APP_NAME" > tmp.$$.json && mv tmp.$$.json app/ionic.config.json
sed -i -e 's@<title>StApps<\/title>@<title>'"$APP_DISPLAY_NAME"'<\/title>@g' app/src/index.html

ROOT_THEME_DEFINITONS=$(cat app/src/theme/variables.scss | grep -o :root | wc -l)

if [ $ROOT_THEME_DEFINITONS -gt 1 ]; then
  #update
  echo "SCSS theme has already been set"
else
  #insert
  cat customizable/theme/variables.scss >> app/src/theme/variables.scss
fi



# capacitor config
awk "/appName:.*,/ && !done { gsub(/appName:.*,/, \"appName: '$APP_NAME',\"); done=1}; 1" app/capacitor.config.ts > tmp.$$.json && mv tmp.$$.json app/capacitor.config.ts
awk "/appId:.*,/ && !done { gsub(/appId:.*,/, \"appId: '$APP_ID',\"); done=1}; 1" app/capacitor.config.ts > tmp.$$.json && mv tmp.$$.json app/capacitor.config.ts

# cordova config
xmlstarlet edit -L --update "/widget/@id" --value  "$APP_ID" app/config.xml
xmlstarlet edit -L --update "/widget/@version" --value "$APP_VERSION" app/config.xml
xmlstarlet edit -L -N x="http://www.w3.org/ns/widgets" --update "//x:name" --value "$APP_NAME" app/config.xml

SHORT_EXISTS=$(xmlstarlet sel -N x='http://www.w3.org/ns/widgets' -T -t -v '//x:name[@short]' app/config.xml)

if [ -z "${SHORT_EXISTS:-}" ]; then
  #insert
  xmlstarlet edit -L -N x="http://www.w3.org/ns/widgets" -s "//x:name" -t attr -n "short" -v "$APP_DISPLAY_NAME" app/config.xml
else
  #update
  xmlstarlet edit -L -N x="http://www.w3.org/ns/widgets" --update "//x:name[@short]" -v "$APP_DISPLAY_NAME" app/config.xml
fi

# environment config
awk "/backend_url:.*,/ && !done { gsub(/backend_url:.*,/, \"backend_url: '$BACKEND_URL',\"); done=1}; 1" app/src/environments/environment.production.ts > tmp.$$.json && mv tmp.$$.json app/src/environments/environment.production.ts
awk "/backend_version:.*,/ && !done { gsub(/backend_version:.*,/, \"backend_version: '$BACKEND_VERSION',\"); done=1}; 1" app/src/environments/environment.production.ts > tmp.$$.json && mv tmp.$$.json app/src/environments/environment.production.ts
awk "/app_host:.*,/ && !done { gsub(/app_host:.*,/, \"app_host: '$APP_LINK_HOST',\"); done=1}; 1" app/src/environments/environment.production.ts > tmp.$$.json && mv tmp.$$.json app/src/environments/environment.production.ts
awk "/custom_url_scheme:.*,/ && !done { gsub(/custom_url_scheme:.*,/, \"custom_url_scheme: '$APP_URL_SCHEME',\"); done=1}; 1" app/src/environments/environment.production.ts > tmp.$$.json && mv tmp.$$.json app/src/environments/environment.production.ts
