#!/bin/bash
# GCPassesFix - Game Center and Passes fix for legacy iOS (LegacyReborn).
#
# Game Center on old iOS stops signing in once Apple rotates TLS roots and
# leaves stale sign-in state behind. The fix from the bag.xml guide
# (developer.bag-xml.com/guides/gamecenter, by fifiisawesum) is two parts:
#   1. install up-to-date root certificates;
#   2. clear the stale Game Center / iTunes Store / setup state so the device
#      boots back into Setup and signs in clean.
# This tool does part 2 safely (everything it removes is copied to a backup
# first and can be restored) and stages the certificate profile for part 1.
#
# Passes (Passbook) is fixed separately by the GCPassesFix MobileSubstrate
# tweak; this tool does not touch it.
#
# The Settings pane runs this through /usr/libexec/gcpassesfix-run and shows
# the output in an alert, so it only relies on bash builtins plus cp, rm,
# mkdir, rmdir, chown, date and sync (all in the always-installed
# coreutils-bin), and prints colours only to a terminal.

set -u

SHARE=/usr/share/gcpassesfix
PROFILE="$SHARE/GCPassesFix-Roots.mobileconfig"
BACKUP_ROOT=/var/mobile/Library/GCPassesFix/backups
STAGE_DIR=/var/mobile/Documents
STAGE="$STAGE_DIR/GCPassesFix-Roots.mobileconfig"

# Home of the user whose state we reset. Overridable for odd setups.
MOBILE="${GCPF_MOBILE:-/var/mobile}"

# Preference files in <mobile>/Library/Preferences to clear.
PREFS=(
	com.apple.gamed.plist
	com.apple.gamecenter.plist
	com.apple.itunesstored.plist
	com.apple.storeuiservice.plist
	com.apple.purplebuddy.plist
	com.apple.assistant.plist
	com.apple.geo.plist
)

# Cache folders/files in <mobile>/Library/Caches to clear.
CACHES=(
	AppStore
	AssistantServices
	aosnotifyd
	assetsd
	dataaccess
	GameCenter
	GamecenteruiService
	GEOservices
	StoreKitUIService
	iTunesStore
	itunesstored
	Preferences
	PurpleBuddy
	GameKit
	com.apple.gamed
)

if [ -t 1 ]; then
	red()   { printf '\033[31m%s\033[0m\n' "$*"; }
	green() { printf '\033[32m%s\033[0m\n' "$*"; }
	bold()  { printf '\033[1m%s\033[0m\n' "$*"; }
else
	red()   { printf '%s\n' "$*"; }
	green() { printf '%s\n' "$*"; }
	bold()  { printf '%s\n' "$*"; }
fi

need_root() {
	if [ "$EUID" -ne 0 ]; then
		red "Needs root. In Terminal run it with su; in Settings reinstall GCPassesFix (its helper lost root rights)."
		exit 1
	fi
}

# Name of the newest backup (names are timestamps, so glob order is age order).
# No arrays here: bash 4.0 on iOS 6 treats an empty array as unbound under set -u.
latest_backup() {
	local d last=""
	for d in "$BACKUP_ROOT"/*/; do
		[ -d "$d" ] || continue
		d="${d%/}"
		last="${d##*/}"
	done
	printf '%s' "$last"
}

cmd_status() {
	local n=0 found=0 any=0 p d
	for p in "$SHARE"/certs/*.cer; do
		[ -e "$p" ] && n=$((n+1))
	done
	bold "GCPassesFix status"
	echo "Bundled certificates: $n"
	if [ -f "$PROFILE" ]; then
		echo "Certificate profile: ready"
	else
		red "Certificate profile: missing"
	fi
	echo
	echo "Sign-in state left to clear:"
	for p in "${PREFS[@]}"; do
		if [ -e "$MOBILE/Library/Preferences/$p" ]; then echo "  $p"; found=1; fi
	done
	for p in "${CACHES[@]}"; do
		if [ -e "$MOBILE/Library/Caches/$p" ]; then echo "  Caches/$p"; found=1; fi
	done
	if [ "$found" = 0 ]; then green "  nothing - a reboot will drop into Setup"; fi
	echo
	for d in "$BACKUP_ROOT"/*/; do
		[ -d "$d" ] || continue
		if [ "$any" = 0 ]; then echo "Backups:"; any=1; fi
		d="${d%/}"
		echo "  ${d##*/}"
	done
	if [ "$any" = 0 ]; then echo "Backups: none"; fi
	return 0
}

cmd_certs() {
	need_root
	if [ ! -f "$PROFILE" ]; then
		red "Certificate profile is missing: $PROFILE. Reinstall GCPassesFix."
		exit 1
	fi
	if [ ! -d "$STAGE_DIR" ]; then
		mkdir -p "$STAGE_DIR" && chown mobile:mobile "$STAGE_DIR" 2>/dev/null
	fi
	if ! cp "$PROFILE" "$STAGE"; then
		red "Could not copy the profile to $STAGE."
		exit 1
	fi
	chown mobile:mobile "$STAGE" 2>/dev/null
	green "Profile saved to $STAGE"
	echo
	echo "To install it, open the file in Filza (or iFile) and tap it, or mail it to yourself and tap the attachment. Then tap Install; iOS marks it Not Verified, as with every community certificate bundle."
}

cmd_reset() {
	need_root
	local stamp backup n=0 p src
	stamp=$(date '+%Y%m%d-%H%M%S' 2>/dev/null)
	[ -n "$stamp" ] || stamp="backup-$$"
	backup="$BACKUP_ROOT/$stamp"
	if ! mkdir -p "$backup/Preferences" "$backup/Caches"; then
		red "Could not create the backup folder $backup."
		exit 1
	fi

	bold "Clearing Game Center / Store / Setup state"
	for p in "${PREFS[@]}"; do
		src="$MOBILE/Library/Preferences/$p"
		[ -e "$src" ] || continue
		if cp -a "$src" "$backup/Preferences/" && rm -rf "$src"; then
			echo "  $p"; n=$((n+1))
		else
			red "  could not clear $p"
		fi
	done
	for p in "${CACHES[@]}"; do
		src="$MOBILE/Library/Caches/$p"
		[ -e "$src" ] || continue
		if cp -a "$src" "$backup/Caches/" && rm -rf "$src"; then
			echo "  Caches/$p"; n=$((n+1))
		else
			red "  could not clear Caches/$p"
		fi
	done

	if [ "$n" = 0 ]; then
		rmdir "$backup/Preferences" "$backup/Caches" "$backup" 2>/dev/null
		green "Nothing left to clear. Reboot and the device starts in Setup."
		return 0
	fi

	echo
	green "Cleared $n item(s); backup $stamp."
	echo "Now reboot: the device starts in Setup, sign in to your Apple ID there. Install the root certificates first."
}

cmd_restore() {
	need_root
	local name="${1:-}" backup f base
	[ -n "$name" ] || name=$(latest_backup)
	case "$name" in
		*/*|.|..) name="" ;;
	esac
	backup="$BACKUP_ROOT/$name"
	if [ -z "$name" ] || [ ! -d "$backup" ]; then
		red "No backup to restore."
		exit 1
	fi

	bold "Restoring backup $name"
	for f in "$backup/Preferences"/*; do
		[ -e "$f" ] || continue
		base="${f##*/}"
		rm -rf "$MOBILE/Library/Preferences/$base"
		cp -a "$f" "$MOBILE/Library/Preferences/" && echo "  $base"
	done
	for f in "$backup/Caches"/*; do
		[ -e "$f" ] || continue
		base="${f##*/}"
		rm -rf "$MOBILE/Library/Caches/$base"
		cp -a "$f" "$MOBILE/Library/Caches/" && echo "  Caches/$base"
	done
	green "Restored. Reboot for it to take effect."
}

cmd_reboot() {
	need_root
	sync
	if command -v reboot >/dev/null 2>&1; then
		reboot
	else
		launchctl reboot
	fi
}

usage() {
	cat <<EOF
GCPassesFix - Game Center and Passes fix for legacy iOS (LegacyReborn)

Usage: gcpassesfix <command>

  status            Show certificates, leftover sign-in state and backups
  certs             Stage the root-certificate profile for installation
  reset             Back up and clear Game Center / Store / Setup state,
                    so the next reboot drops into Setup for a clean sign-in
  restore [NAME]    Restore the most recent (or named) backup
  reboot            Reboot the device
  help              This text

Passes (Passbook) is fixed by the GCPassesFix tweak and needs no command.
EOF
}

case "${1:-help}" in
	status)  cmd_status ;;
	certs)   cmd_certs ;;
	reset)   cmd_reset ;;
	restore) shift; cmd_restore "$@" ;;
	reboot)  cmd_reboot ;;
	help|-h|--help) usage ;;
	*) usage; exit 1 ;;
esac
