#!/usr/bin/env bash
# generate the checksec file from the src directory

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}" && git rev-parse --show-toplevel)"
cd "${REPO_ROOT}" || {
  echo "error: directory does not exist"
  exit 1
}
generated_file="${REPO_ROOT}/checksec"

# add shebang line and edit line
cat << 'EOF' > "${generated_file}"
#!/usr/bin/env bash
# Do not edit this file directly, this file is generated from the files
# in the src directory. Any updates to this file will be overwritten when generated
EOF

# add the header
sed -e '1,3d' "${REPO_ROOT}"/src/header.sh >> "${generated_file}"

# add the core file
sed -e '1,3d' "${REPO_ROOT}"/src/core.sh >> "${generated_file}"

# join all function files together in the middle
while read -r file; do
  # remove the first 3 lines of each source file
  # shebang line is included to properly shellcheck and format
  sed -e '1,3d' "${file}" >> "${generated_file}"
done < <(find "${REPO_ROOT}"/src/functions -type f -iname "*.sh" | sort)

# add the footer
sed -e '1,3d' "${REPO_ROOT}"/src/footer.sh >> "${generated_file}"

# make it executable
chmod 755 "${generated_file}"
