#!/usr/bin/env bash

#= The patch scriptlet is used to apply a patch from the bashinate repository
#= to the specified file on the local system.  Before running the 
#= BASHINATE_PERMISSIONS hash will be checked to ensure the user has 
#= given permission for patch operations to take place.

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

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

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

# apply the patch
log "- patching $PATCH_TARGET"
wget --quiet $BASHINATE_REMOTE/patches/$OS_NAME/$OS_VERSION$PATCH_TARGET -O $TMPFILE && \
patch --backup $PATCH_TARGET < $TMPFILE && \
rm $TMPFILE