#!/bin/sh

##
## Copyright 2013 Cumulus Networks, Inc.
## All rights reserved.
##
## Shell archive template
##
## Strings of the form %%VAR%% are replaced during construction.
##

echo -n "Verifying image checksum ..."
sha1=$(sed -e '1,/^exit_marker$/d' "$0" | sha1sum | awk '{ print $1 }')

payload_sha1=59c46ab9fdc4e3bcd0025456a55c702af799f0fe

if [ "$sha1" != "$payload_sha1" ] ; then
    echo
    echo "ERROR: Unable to verify archive checksum"
    echo "Expected: $payload_sha1"
    echo "Found   : $sha1"
    exit 1
fi

echo " OK."

if [ -n "$verify" ] ; then
    # stop here
    exit 0
fi

# Check if trying deprecated image upgrade option
ppname=$(cat /proc/$PPID/comm)
if [ "$ppname" = "cl-img-install" ]; then
  ppargs=$(cat /proc/$PPID/cmdline | tr "\0" " " | cut -d' ' -f3-)
  save_cmdline=$@
  set -- $ppargs
  while getopts :u a; do
    case $a in
      u)
        echo "\n####################################################################"
        echo "Upgrade functionality (-u option) has been deprecated."
        echo "The target slot has not been modified."
        echo "Please refer to supported upgrade procedures on"
        echo "http://docs.cumulusnetworks.com or contact Cumulus support at "
        echo "https://support.cumulusnetworks.com/hc/en-us for further assistance."
        echo "####################################################################\n"
        exit 1
        ;;
      \?)
        ;;
    esac
  done
  set -- $save_cmdline
fi

# Untar and launch setup script in a tmpfs
cur_wd=$(pwd)
archive_path=$(realpath "$0")

tmp_dir=
clean_up()
{
    cd $cur_wd
    # clean up if not extracting
    if [ -z "$extract" ] ; then
        if [ "$(id -u)" = "0" ] ; then
            umount $tmp_dir
        fi
        rm -rf $tmp_dir
    fi
}

if [ -n "$extract" ] && [ -d "$extract" ] ; then
    tmp_dir=$extract
else
    tmp_dir=$(mktemp -d -p $HOME)
    if [ "$(id -u)" = "0" ] ; then
        mount -t tmpfs tmpfs-installer $tmp_dir || exit 1
    fi
fi
trap clean_up EXIT TERM
cd $tmp_dir || exit 1

echo -n "Preparing image archive ..."
sed -e '1,/^exit_marker$/d' $archive_path | tar xf - || exit 1
echo " OK."
cd $cur_wd
if [ -n "$extract" ] ; then
    # stop here
    echo "Image extracted to: $tmp_dir"
    if [ "$(id -u)" = "0" ] && [ ! -d "$extract" ] ; then
        echo "To un-mount the tmpfs when finished type:  umount $tmp_dir"
    fi
    exit 0
fi

$tmp_dir/installer/install.sh $archive_path "$@"
rc="$?"

exit $rc

exit_marker
