76 lines
1.7 KiB
Bash
Executable File
76 lines
1.7 KiB
Bash
Executable File
#!/bin/sh
|
|
# Script to add a SHA256 checksum to a file
|
|
# Usage: shasumscript <file>
|
|
# Output: <file>_sha256
|
|
# Requires: shasum
|
|
# License: GNU GPL3
|
|
# Author: Patrick Cao Huu Thien
|
|
|
|
set -e
|
|
|
|
error() { printf "Error: \e[31m%s\e[0m\n" "$*" >&2; }
|
|
err() { error "$*"; exit 1; }
|
|
usage() { echo "Usage: $(basename "$0") [-V | -h] <file>";echo " -V: Show version"; echo " -h: Show this help"; }
|
|
err_usage() { error "$*"; usage; exit 1; }
|
|
step () { err="$?"; c=32; t=OK; test "$err" = 0 || { c=31; t=FAILED; }; printf "* %s \e[%dm%s\e[0m\n" "$*" "$c" "$t"; }
|
|
compress() { cat | gzip -9 | base64; }
|
|
|
|
|
|
VERSION="0.0.1"
|
|
if test "$1" = '-V'; then echo "shasumscript v$VERSION"; exit; fi
|
|
if test "$1" = '-h'; then usage; exit; fi
|
|
|
|
file="$1"
|
|
test -n "$file" || err_usage "Missing file argument"
|
|
test -e "$file" || err "File not found: $file"
|
|
|
|
sha="$(shasum -a 256 "$file" | cut -d' ' -f1)" || err "Failed to calculate SHA256 checksum"
|
|
step "Checksum"
|
|
|
|
bin=$(cat "$file" | compress)
|
|
step "Compress"
|
|
|
|
newfile="${file}_sha256"
|
|
|
|
cat <<EOT > "$newfile"
|
|
#!/bin/sh
|
|
# script generated by shasumscript at $(date)
|
|
#
|
|
# This script self-checkssum it's content and exit on error
|
|
# The real script can be found after line 22.
|
|
#
|
|
# License: GNU GPL3
|
|
# Author: Patrick Cao Huu Thien
|
|
|
|
tmpexe="\$(mktemp)"
|
|
trap 'rm -f "\$tmpexe"' EXIT
|
|
|
|
cat "\$0" | sed '1,21d' | base64 -d 2>/dev/null| gunzip 2>/dev/null > "\$tmpexe"
|
|
test "\$(shasum -a 256 "\$tmpexe" | cut -d' ' -f1)" = "$sha" || {
|
|
echo "Checksum mismatch!" >&2
|
|
exit 1
|
|
}
|
|
|
|
sh "\$tmpexe" "\$@"
|
|
|
|
exit
|
|
EOT
|
|
step "pre-script"
|
|
|
|
echo "$bin" >> "$newfile"
|
|
step "post-script"
|
|
|
|
chmod +x "$newfile"
|
|
step "make it executable"
|
|
echo
|
|
cat <<EOT
|
|
File created: $newfile
|
|
|
|
You can distribute it.
|
|
|
|
To run it:
|
|
./$newfile
|
|
EOT
|
|
|
|
|