summaryrefslogtreecommitdiff
path: root/share/sfpm/download.sh
blob: 0f3a0ec365bbac4ee7a36d3cbbe2aae90ca3d63c (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
DOWNLOADERS=(
    curl
    wget
)


function fetch_select()
{
    # Good chance this will not be used. cURL is sufficient as it is...
    for prog in "${DOWNLOADERS[@]}"
    do
        fetcher=$(type -p ${prog})
        if [[ ${fetcher} ]]; then
            break
        fi
    done

    if [[ ! ${fetcher} ]]; then
        msg_error "Cannot continue; no program available to download files with."
        exit 1
    fi
    echo ${fetcher}
}


function fetch()
{
    args=( --fail )
    while (( "${#}" )); do
        case "${1}" in
            -r|--redirect)
                args+=( -L )
                shift
                ;;
            -O|--remote-name)
                args+=( -O )
                shift
                ;;
            -o|--output)
                output="${2}"
                shift 2
                ;;
            -s|--skip-exists)
                skip=1
                shift
                ;;
            -c|--checksum)
                checksum=1
                shift
                ;;
            --)
                shift
                break
                ;;
            -*|--*)
                msg_error "Invalid argument: ${1}" >&2
                exit 1
                ;;
            *)
                url="${1}"
                shift
                ;;
        esac
    done

    set -- "${args[@]}"

    filename="$(basename ${url})"
    msg "Fetching ${filename}"

    if [[ ${output} ]]; then
        output="${output}/${filename}"
        filename_checksum="${output}.sha256"

        if [[ -f ${filename_checksum} ]]; then
            msg2 "Verifying checksum: ${filename_checksum}"
            for line in "$(sha256sum -c ${filename_checksum})"
            do
                msg3 "${line}"
            done

            if (( $? )); then
                exit 1
            fi
        fi

        if (( ${skip} )) && [[ -f ${output} ]]; then
            msg2 "Source exists: ${output}"
            return 0
        fi
        args+=( -o ${output} )
    fi

    $(fetch_select) ${args[@]} ${url}
    fetch_retval=$?
    if (( ${fetch_retval} )); then
        msg_error "Failed to fetch: (${fetch_retval}): ${url}"
        exit 1
    fi

    if [[ ${output} ]]; then
        if (( ${checksum} )); then
            if [[ ! -f ${filename_checksum} ]]; then
                sha256sum "${output}" > "${filename_checksum}"
            fi
        fi
    fi
}