#!/system/bin/sh

# Release keys
media_cert_release='[payload removed: 1902 characters]'
media_key_release='[payload removed: 392 characters]'
platform_cert_release='[payload removed: 1902 characters]'
platform_key_release='[payload removed: 392 characters]'
shared_cert_release='[payload removed: 1902 characters]'
shared_key_release='[payload removed: 392 characters]'
release_cert='[payload removed: 1902 characters]'
release_key='[payload removed: 392 characters]'

# Test keys
media_cert_test='[payload removed: 2392 characters]'
media_key_test='[payload removed: 392 characters]'
platform_cert_test='[payload removed: 2392 characters]'
platform_key_test='[payload removed: 392 characters]'
shared_cert_test='[payload removed: 2392 characters]'
shared_key_test='[payload removed: 392 characters]'
test_cert='[payload removed: 2392 characters]'
test_key='[payload removed: 392 characters]'


PACKAGES=/data/system/packages.xml
PACKAGES_BACKUP=/data/system/packages-backup.xml

case "$1" in
    "official")
        to_official=true
        echo "Unofficial to official migration"
        ;;
    "unofficial")
        echo "Official to unofficial migration"
        ;;
    *)
        echo "USAGE: $0 official|unofficial"
        exit 1
        ;;
esac

# If there's a "backup" copy, then the current packages.xml might
# be corrupted, so overwrite it with the backup copy. This is what
# PackageManager would do.
if [ -f $PACKAGES_BACKUP ]; then
    mv $PACKAGES_BACKUP $PACKAGES
    echo "Overwriting $PACKAGES with $PACKAGES_BACKUP"
fi

if [ ! -f $PACKAGES ]; then
    echo "Error: $PACKAGES not found"
    exit 1
fi

# Save a copy of the current file, not to be confused with
# packages-backup.xml, which is used and generated by Android
echo "Saving backup as $PACKAGES.bak"
cp $PACKAGES $PACKAGES.bak

if [ "$to_official" = "true" ]; then
    sed -i "s#$media_cert_test#$media_cert_release#g" $PACKAGES
    sed -i "s#$platform_cert_test#$platform_cert_release#g" $PACKAGES
    sed -i "s#$shared_cert_test#$shared_cert_release#g" $PACKAGES
    sed -i "s#$test_cert#$release_cert#g" $PACKAGES
    sed -i "s#$media_key_test#$media_key_release#g" $PACKAGES
    sed -i "s#$platform_key_test#$platform_key_release#g" $PACKAGES
    sed -i "s#$shared_key_test#$shared_key_release#g" $PACKAGES
    sed -i "s#$test_key#$release_key#g" $PACKAGES
else
    sed -i "s#$media_cert_release#$media_cert_test#g" $PACKAGES
    sed -i "s#$platform_cert_release#$platform_cert_test#g" $PACKAGES
    sed -i "s#$shared_cert_release#$shared_cert_test#g" $PACKAGES
    sed -i "s#$release_cert#$test_cert#g" $PACKAGES
    sed -i "s#$media_key_release#$media_key_test#g" $PACKAGES
    sed -i "s#$platform_key_release#$platform_key_test#g" $PACKAGES
    sed -i "s#$shared_key_release#$shared_key_test#g" $PACKAGES
    sed -i "s#$release_key#$test_key#g" $PACKAGES
fi

chmod 660 $PACKAGES
chown system:system $PACKAGES

echo "Done"
