#!/bin/sh
# offscreen installer · https://aphonethatcares.com/offscreen
#
# this script does three things, and you can read all of them:
#   1. finds adb on this computer (or downloads google's official
#      platform-tools into a temporary folder — nothing is installed)
#   2. installs offscreen.apk onto the phone plugged in via usb
#   3. runs the one permission command offscreen needs:
#        adb shell pm grant com.ptc.graydawn android.permission.WRITE_SECURE_SETTINGS
#
# the phone needs usb debugging turned on first:
#   settings -> about phone -> tap "build number" seven times,
#   then settings -> system -> developer options -> usb debugging.

set -e

SITE="https://aphonethatcares.com/offscreen"
PKG="com.ptc.graydawn"   # the app's internal id keeps its birth name
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

# --- 1. find or fetch adb --------------------------------------------------
ADB="$(command -v adb || true)"
for CAND in "$HOME/Library/Android/sdk/platform-tools/adb" \
            "$HOME/Android/Sdk/platform-tools/adb"; do
  [ -z "$ADB" ] && [ -x "$CAND" ] && ADB="$CAND"
done

if [ -z "$ADB" ]; then
  case "$(uname -s)" in
    Darwin) PT="platform-tools-latest-darwin.zip" ;;
    Linux)  PT="platform-tools-latest-linux.zip" ;;
    *) echo "this script knows mac and linux. on windows: get platform-tools"
       echo "from developer.android.com, then run the two adb lines shown at"
       echo "$SITE under 'prefer to run it yourself?'."; exit 1 ;;
  esac
  echo "adb isn't on this computer — fetching google's platform-tools (~13 mb, official)..."
  curl -fSL --progress-bar "https://dl.google.com/android/repository/$PT" -o "$TMP/pt.zip"
  unzip -q "$TMP/pt.zip" -d "$TMP"
  ADB="$TMP/platform-tools/adb"
fi

# --- 2. wait for the phone ---------------------------------------------------
echo ""
echo "plug the phone in via usb. if it asks 'allow usb debugging?' — tap allow."
echo "waiting for the phone..."
"$ADB" start-server >/dev/null 2>&1 || true
"$ADB" wait-for-device

# --- 3. install + grant ------------------------------------------------------
echo "fetching offscreen.apk..."
curl -fSL --progress-bar "$SITE/offscreen.apk" -o "$TMP/offscreen.apk"

echo "installing..."
"$ADB" install -r "$TMP/offscreen.apk"

echo "granting the color-switch permission..."
"$ADB" shell pm grant "$PKG" android.permission.WRITE_SECURE_SETTINGS

if "$ADB" shell dumpsys package "$PKG" | grep -q "WRITE_SECURE_SETTINGS.*granted=true"; then
  echo ""
  echo "all set. unplug the phone and open offscreen — it walks you through the rest."
else
  echo ""
  echo "hmm — the permission didn't take. try it by hand:"
  echo "  \"$ADB\" shell pm grant $PKG android.permission.WRITE_SECURE_SETTINGS"
fi
