#!/bin/sh
set -e

PATH=/var/jb/usr/bin:/var/jb/bin:/usr/bin:/bin

mkdir -p /var/jb/var/lib/cydia /var/jb/var/cache/apt/archives/partial

# pdx1 wrote this source even when Sileo already managed the same repository.
# Remove only that exact generated file; never touch a user-managed source.
cydia_list=/var/jb/etc/apt/sources.list.d/cydia.list
if [ -f "$cydia_list" ] && [ ! -L "$cydia_list" ]; then
    nonblank="$(sed '/^[[:space:]]*$/d' "$cydia_list")"
    if [ "$nonblank" = 'deb https://apps.pdxtechs.com/repo/ ./' ]; then
        rm -f "$cydia_list"
    fi
fi

# Keep Cydia's private source cache independent from Sileo's shared source
# directory, but make the PDXTechs repository available to both managers.
# Writing through the existing inode preserves the mobile ownership.
cydia_cache=/var/mobile/Library/Caches/com.saurik.Cydia/sources.list
mkdir -p "$(dirname "$cydia_cache")"
touch "$cydia_cache"
if ! grep -Fqx 'deb https://apps.pdxtechs.com/repo/ ./' "$cydia_cache"; then
    printf '%s\n' 'deb https://apps.pdxtechs.com/repo/ ./' >> "$cydia_cache"
fi

if [ -x /var/jb/usr/libexec/cydia/firmware.sh ]; then
    /var/jb/usr/libexec/cydia/firmware.sh || true
fi

if [ -x /var/jb/usr/bin/uicache ]; then
    /var/jb/usr/bin/uicache -p /var/jb/Applications/Cydia.app || /var/jb/usr/bin/uicache -a || true
fi

exit 0
