summaryrefslogtreecommitdiff
path: root/hashit
blob: 1f08d7e5238f44c607c10d69719a05c10c29c9d7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env bash

set -euo pipefail

# @describe Generate or verify SHA512 checksums
# @meta version 1.0.0
# @meta require-tools sha512sum
# @meta combine-shorts
#
# @flag -s --single-file Use single hash file (default: $HASHIT_SINGLE_FILE_NAME)
# @flag -c --check Verify checksums
# @flag -f --force Overwrite existing hash files
#
# @arg files+ Files to hash or verify
#
# @env HASHIT_SINGLE_FILE_NAME=SHA512SUMS Hash file name for single-file mode

check_file_and_fail() {
  if [ -f "$1" ] && [ -z "${argc_force:-}" ]; then
    echo "error: file '$1' exists; use -f to force overwrite" >&2
    exit 1
  fi
}

main() {
  if [ -n "${argc_single_file:-}" ]; then
    if [ -n "${argc_check:-}" ]; then
      sha512sum -c "$HASHIT_SINGLE_FILE_NAME"
    else
      check_file_and_fail "$HASHIT_SINGLE_FILE_NAME"
      sha512sum "${argc_files[@]?}" >"$HASHIT_SINGLE_FILE_NAME"
    fi
  else
    local hash_file
    if [ -n "${argc_check:-}" ]; then
      for file in "${argc_files[@]?}"; do
        if [[ "$file" == *.sha512 ]]; then
          hash_file="$file"
        else
          hash_file="${file}.sha512"
        fi
        sha512sum -c "$hash_file"
      done
    else
      for file in "${argc_files[@]?}"; do
        hash_file="${file}.sha512"
        check_file_and_fail "$hash_file"
        echo "$(sha512sum "$file" | cut -d ' ' -f 1)  $(basename "$file")" >"$hash_file"
      done
    fi
  fi
}

eval "$(argc --argc-eval "$0" "$@")"