#!/bin/bash
# Copies the current build to the iPhone, removing older Mulberry packages there.
# Installs it too when passwordless sudo is allowed for TrollStore's helper; otherwise prints the command.
set -euo pipefail
cd "$(dirname "$0")/.."
IPHONE=${IPHONE:-mobile@192.168.1.94}
KEY=${IPHONE_KEY:-$HOME/.ssh/iphone_key}
V=$(cat VERSION)
IPA=build/Mulberry-$V-iOS.ipa
ssh_=(ssh -i "$KEY" -o BatchMode=yes -o ConnectTimeout=10 "$IPHONE")
"${ssh_[@]}" 'rm -f /var/mobile/mulberry-build/Mulberry-*.ipa /var/mobile/mulberry-build/Mulberry-*.deb'
scp -q -i "$KEY" "$IPA" "build/Mulberry-$V-iOS-rootless.deb" "$IPHONE:/var/mobile/mulberry-build/"
HELPER=/var/jb/Applications/TrollStoreLite.app/trollstorehelper
if "${ssh_[@]}" "sudo -n $HELPER install /var/mobile/mulberry-build/$(basename "$IPA")" 2>/dev/null; then
    echo "installed Mulberry $V"
else
    echo "copied Mulberry $V; install with:"
    echo "  sudo $HELPER install /var/mobile/mulberry-build/$(basename "$IPA")"
    echo "then (fixes black widgets after an update):"
    echo "  uicache -p /var/containers/Bundle/Application/*/Mulberry.app && killall chronod"
fi
