Cannot restore an adb backup due to a tarball with a broken header
After a whole day of various experiments with another tools like TitaniumBackup (neither worked nice, TB was only able to restore APKs, not data) I've figured out that specifying the -apk key was the problem. Simply omitting the flag during a backup operation makes it fully restorable.

So my new backup/restore plan became as follows:


device 1: backup data only
device 2: backup APK+data retaining the APK only later (requires nelenkov/android-backup-exractor by Nikolay Elenkov; can be easily built using JDK 1.8.x and Gradle 2.7 (couldn't build it using Gradle 2.7+ and Gradle 3.0+) with simple gradle command)
device 2: restore the APK using adb install
device 2: restore the data using adb restore


Here are the scripts:

backup.sh



#!/bin/bash

set -e

PACKAGE=$1

if [ -z "$PACKAGE" ]; then
    echo no package specified
    exit
fi

echo "&gt;&gt;&gt; Backing up $PACKAGE data..."
adb backup -f "$PACKAGE".DATA.ab $PACKAGE

echo "&gt;&gt;&gt; Backing up $PACKAGE APK..."
adb backup -apk -f "$PACKAGE".APK.ab $PACKAGE

echo "&gt;&gt;&gt; Extracting APK..."
java -jar abe-all.jar unpack "$PACKAGE".APK.ab "$PACKAGE".APK.ab.tar
rm "$PACKAGE".APK.ab
APK_FILENAME=$(basename $(tar tf "$PACKAGE".APK.ab.tar | grep '^apps/'"$PACKAGE"'/a/'))
tar xvf "$PACKAGE".APK.ab.tar -C ./ "apps/$PACKAGE/a/$APK_FILENAME" --strip-components=3
mv "$APK_FILENAME" "$PACKAGE".apk
rm "$PACKAGE".APK.ab.tar

echo
echo "*************"
echo "*** Done ***"
echo "*************"


This script requires a package name as the input parameter and stores an APK and its data as foo.bar.apk and foo.bar.DATA.ab respectively. I also implemented it as a twice-backup script (a device asks for making a backup two times) because I didn't want to re-pack underlying tarballs preserving the original file order just making sure that the DATA.ab file is in its original state.

restore.sh



#!/bin/bash

set -e

PACKAGE=$1

if [ -z "$PACKAGE" ]; then
    echo no package specified
    exit
fi

echo "&gt;&gt;&gt; Installing $PACKAGE APK..."
adb install -r $PACKAGE.apk

echo "&gt;&gt;&gt; Restoring $PACKAGE data..."
adb restore $PACKAGE.DATA.ab

echo
echo "*************"
echo "*** Done ***"
echo "*************"


This script simply installs an APK on a target device and restores its data. The only input parameter is the application package name.

So the overall backup/restore process is:


Connect device #1
Execute backup.sh passing an application package name
Click "Backup..." on the device #1 (one will be asked two times for the data and APK+data backups respectively)
Repeat the previous two steps for other packages if necessary
Disconnect the device #1 and connect the  device #2
Execute restore.sh passing an application package name
Click "Restore..." on the device #2 once asked
Repeat the previous two steps for other packages if necessary