#!/usr/bin/bash
# If there's a startup-config embedded in the (signed) image, write it to /mnt/flash
# Also wipe /mnt/flash of any untrusted files, since there are some unsigned files
# that could theoretically alter the config (ie /mnt/flash/rc.eos)

dest="/mnt/flash/startup-config"
srcdir="/export/swi/"
sc="startup-config"
scxz="startup-config.xz"

wipe_mnt_flash() {
    cd /mnt/flash
    running_swi=`grep -oP "(?<=SWI=flash:/)(.*)" boot-config | tr '\n' ' '`
    trusted_files=".boot-image.swi startup-config kernel-params boot-config persist debug schedule lost+found .extensions boot-extensions enable3px.key ${running_swi}"
    comm -2 -3 <(ls -a) <(echo $trusted_files | tr ' ' '\n' | sort) | tail -n +3 | xargs rm -rf    
}

if [ -f $srcdir$sc ]; then
    [ -f $srcdir$scxz ] && echo "Warning: both $sc and $scxz in boot image, using $sc"
    echo "Writing signed $sc from boot image to $dest and deleting untrusted files"
    cp -f $srcdir$sc $dest
    wipe_mnt_flash
elif [ -f $srcdir$scxz ]; then
    echo "Writing signed $scxz from boot image to $dest and deleting untrusted files"
    xz -dc $srcdir$scxz > $dest
    wipe_mnt_flash
fi
