#!/usr/bin/env sh

. $PWD/app.conf

# iOS universal link file generation
if [ -z "$TEAM_ID" ] && [ -z "$IOS_BUNDLE_IDENTIFIER" ]
then
  echo "Unable to find Apple Team ID and bundle identifier. Skipping apple-app-site-association generation..."
else
  file_content=$(cat <<EOF
{
  "applinks": {
    "details": [
      {
        "appIDs": [ "${TEAM_ID}.${IOS_BUNDLE_IDENTIFIER}"],
        "components": [
          {
            "/": "/*",
            "comment": "Match all links"
          }
        ]
      }
    ]
  }
}
EOF
)
echo $file_content > $PWD/app/www/.well-known/apple-app-site-association
fi


# Google Play/Android universal link file generation
KEYTOOL_INFO=$(keytool -list -v -keystore ./playstore.keystore -alias $ANDROID_KEYSTORE_KEY_ALIAS -storepass $ANDROID_KEYSTORE_PASSWORD -keypass $ANDROID_KEYSTORE_KEY_PASSWORD || true)
CERT_FINGERPRINT=$(echo $KEYTOOL_INFO | grep -Po '(?:[a-fA-F0-9]{2}:){31}[a-fA-F0-9]{2}')

if [ -z "$CERT_FINGERPRINT" ]
then
  echo "Unable to retrieve Android sigining SHA256 fingerprint. Skipping assetlinks.json generation..."
else
  file_content=$(cat <<EOF
[
  {
    "relation": [
      "delegate_permission/common.handle_all_urls"
    ],
    "target": {
      "namespace": "android_app",
      "package_name": "${ANDROID_PACKAGE_NAME}",
      "sha256_cert_fingerprints": [
        "${CERT_FINGERPRINT}"
      ]
    }
  }
]
EOF
)
echo $file_content > $PWD/app/www/.well-known/assetlinks.json
fi
