#!/usr/bin/awk -f
#
# Download an url target to be seen offline.
# Thus, linked data as img, video, audio, css are
# retrieved and stored in a folder names "timestamp-domain-data"
# for offline browsing.
#
# deps: curl, openssl, yt-dlp

function usage()
{
  printf "usage : %s \"protocol://url.tld/file.smt\"\n" \
    "sw_forlater"
  exit 1
}

function err(msg)
{
  printf "err: %s\n", msg > "/dev/stderr"
  exit 1
}

function warn(msg)
{
  printf "warn: %s\n", msg
}

function fetch_n_replace_data(line)
{
  # n_skip : number of char to skip. i.e "href=" is 5 char

  # look in each "word", space is the separator
  fields = split(line, words, " ")
  for (w=1; w<=fields; w++) {

    link = ""
    before = ""
    closetag = 0

    if (match(tolower(words[w]), "href=.*\.css")) {
      n_skip = 5 # length("href=") = 5
    } else if (match(tolower(words[w]), "src=")) {
      n_skip = 4 # length("src=") = 4
    } else {
      # nothing special
      printf "%s ", words[w] > out_file
      continue
    }

    if (RSTART != 0) {

      link = substr(words[w], RSTART + n_skip)
      before = substr(words[w], 1, RSTART + n_skip - 1)

      # link can be quoted or not
      closetag += sub("/\>$", "", link)
      closetag += sub("\>$", "", link)
      gsub("\"", "", link)
      gsub("'", "", link)

      # build url of data
      if (substr(link, 1, 2) == "//") {
        # no protocol specified: //
        data_url = sprintf("%s:%s", protocol, link)

      } else if (substr(link, 1, 1) == "/") {
        # no domain specified: /
        data_url = sprintf("%s://%s%s",
          protocol, domain, link)

      } else {
        # relative link : use current url without filename
        n = split(url, a, "/")
        for (i = 4; i < n; i++) {
          path = sprintf("%s/%s", path, a[i])
        }
        data_url = sprintf("%s://%s%s/%s",
          protocol, domain, path, link);
      }

      # get filename
      n = split(link, a, "/")
      data_file_name = a[n]
      # clean filename of weird chars
      gsub("[^[:alnum:]\.-_]","-", data_file_name)
      if (data_file_name == "") {
        warn(sprintf("skip:%s - weird path", link))
        continue
      }

      # ensure data_dir exists
      system(sprintf("mkdir -p %s", data_dir))

      # download data
      fetch_n_replace_data_cmd = sprintf("%s '%s' > '%s/%s'",
        fetch_cmd, data_url, data_dir, data_file_name )
      system(fetch_n_replace_data_cmd)

      # echo appropriate html
      printf("%s\"%s/%s\" ",\
        before, data_dir, data_file_name) > out_file
      if (closetag) {
        printf "/>" > out_file
      }
    }
  }
}

function fetch(url)
{
  # different behaviour if it's a html page or another file type
  if ((protocol ~ /^http(s)?/) && (out_file ~ /\.(x)?htm(l)?/)) {

    cmd = sprintf("%s '%s'", fetch_cmd, url);
    while ((cmd | getline) == 1) {
      # comments
      if (match($0, /-->/)) {
        $0 = substr($0, RSTART + 3)
        comment = 0
      } else if (comment) { 
        continue
      }
      if (match($0, /<!--/)) {
        $0 = substr($0, 1, RSTART-1)
        comment = 1
      }
      
      if (match(tolower($0), /<link.* href=.*\.css.*| src=/)) {
        fetch_n_replace_data($0)
      } else {
        print > out_file
      }
    }

  } else {

    cmd = sprintf("%s '%s' > '%s'", fetch_cmd, url, out_file);
    # just download the file
    system(cmd)
  }
  close(cmd)
}

BEGIN {
  if ( ARGC != 2 ) { usage() } # ensure we have ARGV[1]

  # set defaults, override with -v option_name="new value"
  if (fetch_cmd == "") { 
    fetch_cmd = "sw_anyget"
  }
  if (youtube_fetch_cmd == "") { 
    youtube_fetch_cmd = "yt-dlp"
  }

  # check if it is an url
  if (match(ARGV[1], "^(https?|gemini|gopher)://") == 0) {
    err("It doesn't look like a valid url")
  }
  url = ARGV[1]

  # parse url
  split(url, a, ":")
  protocol = a[1]

  n = split(url, a, "/")
  domain = a[3]
  if ((n == 3) || (a[n] == "")) {
    if (protocol ~ /^http(s)?/) {
      file_name = "index.html"
    } else if (protocol == "gemini") {
      file_name = "index.gmi"
    } else if (protocol == "gopher") {
      file_name = "index.txt"
    }
  } else {
    file_name = a[n]
  }
  # replace unwanted chars for filename
  gsub("[^[:alnum:]\.-_]","-", file_name)

  # set paths
  out_file = sprintf("%s-%s-%s", systime(), domain, file_name)
  data_dir = sprintf("%s-data", out_file)

  if (url ~ /http(s)?:\/\/(www\.)?(youtube.com|youtu.be)/) {
    cmd = sprintf("%s '%s'", youtube_fetch_cmd, url)
    system(cmd)
  } else {
    fetch(url)
  }
}
