#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

guard_sourcing

#######################################
# Wrapper for secure curl.
# Globals:
#   ERR_DOWNLOAD_FAILED
#   ERR_NO_DOWNLOAD_ARG
# Arguments:
#   1: URL from which to download a specific file.
#   2: /path/to/file to be saved to.
# Returns:
#   ERR_DOWNLOAD_FAILED: Download failed.
#   ERR_NO_DOWNLOAD_ARG: No arguments specified.
#######################################
scurl() {
  if [[ $# -ne 2 ]]; then
    do_log "error" "true" "Usage: scurl <URL> <path/to/file>"
    return "${ERR_NO_DOWNLOAD_ARG}"
  fi
  declare url="$1"
  declare output_path="$2"
  if ! curl --doh-url "https://dns01.eddns.eu/dns-query" \
            --doh-cert-status \
            --tlsv1.3 \
            -sSf \
            -o "${output_path}" \
            "${url}"
  then
    do_log "error" "true" "Download failed for URL: '${1}'."
    return "${ERR_DOWNLOAD_FAILED}"
  fi
}

#######################################
# Wrapper for secure wget.
# Globals:
#   ERR_DOWNLOAD_FAILED
#   ERR_NO_DOWNLOAD_ARG
# Arguments:
#   1: URL from which to download a specific file.
#   2: /path/to/file to be saved to.
# Returns:
#   ERR_DOWNLOAD_FAILED: Download failed.
#   ERR_NO_DOWNLOAD_ARG: No arguments specified.
#######################################
swget() {
  if [[ $# -ne 2 ]]; then
    do_log "error" "true" "Usage: swget <URL> <path/to/file>"
    return "${ERR_NO_DOWNLOAD_ARG}"
  fi
  declare url="$1"
  declare output_path="$2"
  if ! wget --show-progress \
            --no-clobber \
            --https-only \
            --secure-protocol=TLSv1_3 \
            -qO "${output_path}" \
            "${url}"
  then
    do_log "error" "true" "Download failed for URL: '${1}'."
    return "${ERR_DOWNLOAD_FAILED}"
  fi
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
