# vim: set ft=sh:

run_hook() {
    if [[ -n "${ip}" && -n "${artix_http_srv}" ]]; then

        # booting with http is always copy-to-ram, so set here to make sure
        # addresses are flushed and interface is set down
        copytoram="y"

        artix_http_srv=$(eval echo ${artix_http_srv})
        [[ -z "${artix_http_spc}" ]] && artix_http_spc="75%"

        mount_handler="artix_pxe_http_mount_handler"
    fi
}

# Fetch a file with CURL
#
# $1 URL
# $2 Destination directory inside httpspace/${root}
_curl_get() {
    local _url="${1}"
    local _dst="${2}"

    msg ":: Downloading '${_url}'"
    if ! curl -L -f -o "${live_root}/httpspace/${root}${_dst}/${_url##*/}" --create-dirs "${_url}"; then
        echo "ERROR: Downloading '${_url}'"
        echo "   Falling back to interactive prompt"
        echo "   You can try to fix the problem manually, log out when you are finished"
        launch_interactive_shell
    fi
}

_get_sfs() {
    local _sfs="${1}"
    local _src=${artix_http_srv}${root}
    if [[ ! -z "$( curl -s --head "${_src}/${_sfs}.img" | grep "OK" )" ]]; then
        _curl_get "${_src}/${_sfs}.img" "/"

        if [[ "${checksum}" == "y" ]]; then
            _curl_get "${_src}/${_sfs}.md5" "/"
        fi
        if [[ "${verify}" == "y" ]]; then
            _curl_get "${_src}/${_sfs}.img.sig" "/"
        fi
    fi
}

artix_pxe_http_mount_handler () {
    newroot="${1}"

    msg ":: Mounting ${live_root}/httpspace (tmpfs) filesystem, size='${artix_http_spc}'"
    mkdir -p "${live_root}/httpspace"
    mount -t tmpfs -o size="${artix_http_spc}",mode=0755 httpspace "${live_root}/httpspace"

    _get_sfs "rootfs"
    [[ -n "${overlay}" ]] && _mount_root_overlayfs "${overlay}"

    mkdir -p "${bootmnt}"
    mount -o bind ${live_root}/httpspace ${bootmnt}

    artix_mount_handler ${newroot}
}
