#!/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

# Remove the same automatically-added line from Cydia's private source cache.
# Writing back through the existing inode preserves the mobile ownership.
cydia_cache=/var/mobile/Library/Caches/com.saurik.Cydia/sources.list
if [ -f "$cydia_cache" ]; then
    cache_tmp=/var/jb/tmp/cydia-sources-pdx2.$$
    sed '\|^deb https://apps\.pdxtechs\.com/repo/ \./$|d' "$cydia_cache" > "$cache_tmp"
    if ! cmp -s "$cache_tmp" "$cydia_cache"; then
        cat "$cache_tmp" > "$cydia_cache"
    fi
    rm -f "$cache_tmp"
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
