#!/usr/bin/env bash

#= The systemupdate scriptlet is used to replace a core system file with a
#= replacement file stored in the bashinate repository. This isn't something
#= that should be done lightly and is not recommended in most cases given
#= the potential security risk.

local PATCH_TARGET=$1
local TMPFILE=/tmp/$RANDOM.patch

# check for the patch permissions
[[ ${BASHINATE_PERMISSIONS[systemupdate]} ]] || abort "systemupdate permissions not granted - if you want to allow patches include the allow systemupdate in your recipe"

# ensure that we have write access to the target
[[ -w $PATCH_TARGET ]] || abort "No write access to $PATCH_TARGET, unable to update"

# save a copy of the patch target
cp $PATCH_TARGET $PATCH_TARGET~

# apply the patch
log "- replacing $PATCH_TARGET with bashinate version"
wget --quiet $BASHINATE_REMOTE/system$PATCH_TARGET -O $TMPFILE && \
cp $TMPFILE $PATCH_TARGET && \
rm $TMPFILE