#!/bin/bash

patch="0000b710: be01 0000 0048 89c7 6690 6690 9066 9066
0000b720: 9049 89e4 488d 7d28 4c89 e6e8 10be ffff
0000e0a0: 31f6 4889 c7b8 0100 0000 84c0 0f84 4e01
0000e0d0: ffb8 0100 0000 84c0 0f84 f200 0000 488d
0000e110: ffb8 0100 0000 6690 9048 85c0 0f84 ae01
0000e130: 488b bd10 feff ffb8 0100 0000 84c0 0f84
000135f0: 3030 3030 302d 3030 3030 2d30 3030 302d"

target=/var/packages/CodecPack/target/usr/lib/libsynoame-license.so

hash=$(md5sum "$target" | awk '{print $1}')
if [ "$hash" != "09e3adeafe85b353c9427d93ef0185e9" ]; then
  if [ "$hash" != "79012a151a9af8d808d3410c2eb6297d" ]; then
    echo target $target hash not match
    exit 1
  else
    echo target $target is already patched
  fi
else
  echo "$patch" | xxd -r - $target
fi

json=/usr/syno/etc/license/data/ame/offline_license.json
apparmor=/var/packages/CodecPack/target/apparmor

mkdir -p "/usr/syno/etc/license/data/ame"
echo '[{"appType": 14, "appName": "ame", "follow": ["device"], "server_time": 1666000000, "registered_at": 1651000000, "expireTime": 0, "status": "valid", "firstActTime": 1651000001, "extension_gid": null, "licenseCode": "0", "duration": 1576800000, "attribute": {"codec": "hevc", "type": "free"}, "licenseContent": 1}, {"appType": 14, "appName": "ame", "follow": ["device"], "server_time": 1666000000, "registered_at": 1651000000, "expireTime": 0, "status": "valid", "firstActTime": 1651000001, "extension_gid": null, "licenseCode": "0", "duration": 1576800000, "attribute": {"codec": "aac", "type": "free"}, "licenseContent": 1}]' > "${json}"

/usr/syno/etc/rc.sysv/apparmor.sh remove_packages_profile 0 CodecPack

# disable apparmor check for AME
if [ -e "${apparmor}" ]; then
  mv -f "${apparmor}" "${apparmor}.bak"
fi

/var/packages/CodecPack/target/usr/bin/synoame-bin-auto-install-needed-codec
