#################################################
# Some useful functions to access webpages 	#
# through Darwin.				#
#			Adrian Schneider, 2006	#
#            rewritten  Adrian Altenhoff, 2016  #
#################################################

module external ReadURL, DownloadURL;

wget := proc(url:string, filename:string, timeout:posint)
cmd := 'wget -q -O '.filename.' "'.url.'"';
t := TimedCallSystem(cmd, timeout);
if t[1]<>0 then
    # if it fails, try again non-quiet to catch the error msg
    t := TimedCallSystem('wget -O '.filename.' "'.url.'"', timeout);
    error('wget failed');
elif filename='-' then
    return(t[2]);
else return(NULL);
fi;
end:

curl := proc(url:string, filename:string; timeout:posint)
cmd := 'curl -L -s -S -o '.filename.' --write-out "%{http_code}" "'.url.'"';
t := TimedCallSystem(cmd, timeout);
if t[1] <> 0 then
    # if it fails, try again non-quiet to catch the error msg
    error('curl failed: '.t[2]);
elif t[2, -3]<>'2' then 
    # http code was not 2xx, report error
    error('curl failed: response code: '.t[2,-3..-1]);
else
    if filename='-' then 
        return(t[2,1..-4]);
    else return(NULL) fi:
fi:
end:

SelectWebLibrary := proc()
    t := CallSystem('which wget > /dev/null');
    if t=0 then return(wget); fi:
    t := CallSystem('which curl > /dev/null');
    if t=0 then return(curl); fi:
    error('Either ''wget'' or ''curl'' needs to be installed to download files from the web.');
end:
     

# Read in a URL as a string (like ReadRawFile)
ReadURL := proc(url:string; timeout:posint)
    web := SelectWebLibrary():
    # timout after max one week
    return(web(url, '-', If(assigned(timeout), timeout, 604800))):
end:

# Download a URL into a file
DownloadURL := proc(url:string, filename:string; timeout:posint)
    web := SelectWebLibrary():
    # timout after max one week
    return(web(url, filename, If(assigned(timeout), timeout, 604800))):
end:

end: #module
