#!/bin/sh

entry_index () {
  line="$1"
  index=$2
  log=$(printf "%s" "$line" | awk -F'\t' '{print $2}')
  loghtml=$(printf "%s" "$log" | sed 's/\.[^.]*$//')
  logdir=$(dirname "$log")
  title=$(printf "%s" "$line" | awk -F'\t' '{print $1}' | sed 's|^.||')
  itemnum=$((logcount-index+1))
  page=$(( index / logs_per_page + 1 ))
  if [ "$page" -ne 1 ]; then
    entry_index_html="/var/www/html/log/index-${page}.html"
  else
    entry_index_html="${log_html}"
  fi
  # print link in listings
  if [ "$index" -lt 20 ]; then
    printf "<a href=\"%s.html\">%s <span class=\"dim\">&gt;&gt;</span> %s</a>\\n" "$loghtml" "$itemnum" "$title" >> "${root_index_html}"
  fi
  printf "<a href=\"%s.html\">%s <span class=\"dim\">&gt;&gt;</span> %s</a>\\n" "$loghtml" "$itemnum" "$title" >> "${entry_index_html}"

  # create entry
  entry_html="${html_dir}${loghtml}.html"
  mkdir -p "${html_dir}${logdir}"
  cat "$web_header_html" > "${entry_html}"
  {
    printf "    <title>%s</title>\\n" "$title"
    printf "    <link rel=\"canonical\" href=\"https://cosmic.voyage%s.html\">\\n" "$loghtml"
    cat "$web_styles_html"
    printf "</head>\\n<body>\\n<div class=\"page-wrapper\"><pre class=\"inner-wrapper\">\\n"
    printf "<a href=\"/log\"><span class=\"dim\">&lt;&lt;</span> BACK TO RELAY ONE LOG</a>\\n\\n\\n"
    sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'"'"'/\&#39;/g' "${gopher_dir}${log}"
    # close up the entry footer
    printf "</pre></div></body></html>"
  } >> "${entry_html}"
}

run_user=$(id -un)
if [ "$run_user" = "root" ] || [ "$run_user" = "publish" ]; then
  SCRIPT=$(readlink -f "$0")
  SCRIPTPATH=$(dirname "$SCRIPT")

  root_index_html="/var/www/html/index.html"
  log_html="/var/www/html/log/index.html"
  web_header_html="/etc/templates/webheader.tmpl"
  web_styles_html="/etc/templates/webstyles.tmpl"
  ships_html="/var/www/html/ships/index.html"
  error_html="/var/www/html/error.html"
  join_html="/var/www/html/join.html"
  html_dir="/var/www/html"
  gopher_dir="/var/gopher"
  logcount=$(wc -l "${gopher_dir}/listing.gophermap" | awk '{print $1}')
  logs_per_page=100

  if [ "$1" = "safe" ]; then
    root_date=$(stat -c %Y "$root_index_html")
    listing_date=$(stat -c %Y "${gopher_dir}/listing.gophermap")
    if [ "$listing_date" -lt "$root_date" ]; then
      printf "Listings not updated. Abort\\n"
      exit
    fi
  fi
  # Clear web folder
  rm -rf "/var/www/html/*"
  # Generate RSS
  # shellcheck source=rss
  # shellcheck disable=SC1091
  . "${SCRIPTPATH}/rss"

  # prep directories
  mkdir -p "$(dirname "${log_html}")"

  # Add standard header
  cat "$web_header_html" > "${root_index_html}"
  # Custom header elements and body start
  {
    printf "<title>Cosmic Voyage - Messages from Humanity's Stellar Diaspora</title>"
    printf "<link rel=\"canonical\" href=\"https://cosmic.voyage\">"
    printf "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"Cosmic Voyage\" href=\"/rss.xml\">"
    printf "<meta name=\"description\" content=\"Cosmic Voyage is a public-access unix system and 'tilde' community based around a collaborative science-fiction universe. Users write stories as the people aboard ships, colonies, and outposts, using the only remaining free, interconnected network that unites the dispersed peoples of the stars.\">"
    cat "$web_styles_html"
    printf "</head>"
    printf "<body>"
    printf "<a rel=\"me\" href=\"https://tilde.zone/@cosmicvoyage\" style=\"display: none; visibility: hidden;\" aria-hidden=\"true\">a link to our mastodon account, to verify it as legitimate</a>"
    printf "<div class=\"page-wrapper\">"
    printf "<pre class=\"inner-wrapper\">"
    # Intro text
    cat "${gopher_dir}/intro.gophermap"
    printf "\\n<a href=\"/join.html\"><span class=\"dim\">&gt;&gt;</span> How to Join Cosmic Voyage</a>\\n"
    printf "<a href=\"/log\"><span class=\"dim\">&gt;&gt;</span> Complete Transmission Log</a>\\n"
    printf "<a href=\"/ships\"><span class=\"dim\">&gt;&gt;</span> Ships, Colonies, Outposts</a>\\n"
    printf "<a href=\"/rss.xml\"><span class=\"dim\">&gt;&gt;</span> RSS Feed</a>\\n\\n"
    # Logs
    printf "Most recent log entries:\\n"
  } >> "${root_index_html}"

  pages=$((logcount / logs_per_page + 1))
  for i in $(seq 1 $pages); do
    local_log_html="${log_html}"
    if [ "$i" -gt 1 ]; then
      local_log_html="/var/www/html/log/index-${i}.html"
    fi
    cat "$web_header_html" > "${local_log_html}"
    # Custom header elements and body start
    {
      printf "<title>Cosmic Voyage - Transmission Log</title>"
      printf "<link rel=\"canonical\" href=\"https://cosmic.voyage/log\">"
      cat "$web_styles_html"
      printf "</head>"
      printf "<body>"
      printf "<div class=\"page-wrapper\">"
      printf "<pre class=\"inner-wrapper\">"
      printf "<a href=\"/\"><span class=\"dim\">&lt;&lt;</span> BACK TO RELAY ONE</a>\\n\\n"
      # Intro text
      cat "${gopher_dir}/log/intro.gophermap"
    } >> "$local_log_html"
  done

  # Loop through listings gophermap
  loop=0
  while read -r line; do
    loop=$((loop+1))
    entry_index "$line" $loop
  done < "${gopher_dir}/listing.gophermap"

  for i in $(seq 1 $pages); do
    next=$((i+1))
    prev=$((i-1))
    if [ "$i" -gt 1 ]; then
      local_log_html="/var/www/html/log/index-${i}.html"
    else
      local_log_html="${log_html}"
    fi

    # If there are more pages or previous pages, add nav
    printf "\\n" >> "${local_log_html}"
    if [ "$i" -lt "$pages" ]; then
      printf "<a href=\"index-%s.html\"><span class=\"dim\">&gt;&gt;</span> Older Entries</a>\\n" "$next" >> "${local_log_html}"
    fi
    if [ "$i" -gt 1 ]; then
      if [ "$prev" -eq 1 ]; then
        printf "<a href=\"index.html\"><span class=\"dim\">&gt;&gt;</span> Newer Entries</a>\\n" >> "${local_log_html}"
      else
        printf "<a href=\"index-%s.html\"><span class=\"dim\">&gt;&gt;</span> Newer Entries</a>\\n" "$prev" >> "${local_log_html}"
      fi
    fi

    {
      printf "</pre>\\n"
      printf "</div>\\n"
      printf "</body>\\n"
      printf "</html>"
    } >> "${local_log_html}"
  done

  {
    printf "</pre>\\n"
    printf "</div>\\n"
    printf "</body>\\n"
    printf "</html>"
  } >> "${root_index_html}"

  # Generate ship pages
  mkdir -p "${html_dir}/ships"
  # Add header info to html output
  cat "$web_header_html" > "${ships_html}"
  # Custom header elements and body start
  {
    printf "<title>Cosmic Voyage - Ships</title>"
    printf "<link rel=\"canonical\" href=\"https://cosmic.voyage/ships\">"
    cat "$web_styles_html"
    printf "</head>"
    printf "<body>"
    printf "<div class=\"page-wrapper\">"
    printf "<pre class=\"inner-wrapper\">"
    printf "<a href=\"/\"><span class=\"dim\">&lt;&lt;</span> BACK TO RELAY ONE</a>\\n"
    ship_intro="${gopher_dir}/ships/ships.gophermap"
    if [ -f "$ship_intro" ]; then
      cat "$ship_intro"
      printf "\\n"
    fi
  } >> "${ships_html}"
  # Add header info to html output
  find "${gopher_dir}/" -maxdepth 1 ! -path "${gopher_dir}/" ! -path "${gopher_dir}/ships" ! -path "${gopher_dir}/log" -type d -print |
    sed 's|/var/gopher/||' |
    sort |
    while read -r ship
  do
    entry_num=$(grep -c "^0${ship}" "${gopher_dir}/listing.gophermap")
    if [ "$entry_num" != "0" ]; then
      printf "<a href=\"/ships/%s/\"><span class=\"dim\">&gt;&gt;</span> %s <span class=\"dim\">(%s logs)</span></a>\\n" "$ship" "$ship" "$entry_num" >> "$ships_html"
      # Create individual ship log page
      ship_html="${html_dir}/ships/${ship}/index.html"
      mkdir -p "${html_dir}/ships/${ship}"
      # Add header info to html output
      cat "$web_header_html" > "${ship_html}"
      # Custom header elements and body start
      {
        printf "<title>Cosmic Voyage - %s</title>" "$ship"
        printf "<link rel=\"canonical\" href=\"https://cosmic.voyage/ships/%s\">" "$ship"
        cat "$web_styles_html"
        printf "</head>"
        printf "<body>"
        printf "<div class=\"page-wrapper\">"
        printf "<pre class=\"inner-wrapper\">"
        # Contents
        printf "<a href=\"/ships\"><span class=\"dim\">&lt;&lt;</span> BACK TO RELAY ONE SHIP LIST</a>\\n\\n\\n"

        # Ship Description
        desc="${gopher_dir}/${ship}/.description"
        if [ -f "$desc" ]; then
          cat "$desc"
          printf "\\n"
        fi

        # Ship about page
        about="${gopher_dir}/${ship}/ABOUT"
        if [ -f "$about" ]; then
          about_html="${html_dir}/ships/${ship}/about.html"
          cat "$web_header_html" > "${about_html}"
          {
            printf "<title>Cosmic Voyage - About %s</title>" "${ship}"
            printf "<link rel=\"canonical\" href=\"https://cosmic.voyage/ships/%s/about.html\">" "${ship}"
            cat "$web_styles_html"
            printf "</head>"
            printf "<body>"
            printf "<div class=\"page-wrapper\">"
            printf "<pre class=\"inner-wrapper\">"
            printf "<a href=\"/ships/%s/\"><span class=\"dim\">&lt;&lt;</span> BACK TO SHIP</a>\\n\\n\\n" "${ship}"
            cat "$about"
            printf "</pre></div></body></html>"
          } >> "${about_html}"
          printf "<a href=\"%s\">About %s</a>\\n\\n" "/ships/${ship}/about.html" "$ship"
        fi

        # Ship logs
        printf "%s - Ship Log\\n" "$ship"
        tac "${gopher_dir}/listing.gophermap" |
          awk -v tot="${logcount}" '{gsub("^0",NR" <span class=\"dim\">\\&gt;\\&gt;</span> ",$0);print $0}' |
          grep -E "[0-9]+.*span>\\ ${ship}" |
          awk -F"\\t" '{f=$2; gsub(".txt", ".html", f); printf "<a href=\"%s\">%s</a>\n", f, $1}'

        # Author copyright and optional link
        auth="/var/gopher/${ship}/AUTHOR"
        if [ -f "$auth" ]; then
          author_html="${html_dir}/ships/${ship}/author.html"
          cat "$web_header_html" > "${author_html}"
          {
            printf "<title>Cosmic Voyage - \"%s\" Author</title>" "${ship}"
            printf "<link rel=\"canonical\" href=\"https://cosmic.voyage/ships/%s/author.html\">" "${ship}"
            cat "$web_styles_html"
            printf "</head>"
            printf "<body>"
            printf "<div class=\"page-wrapper\">"
            printf "<pre class=\"inner-wrapper\">"
            printf "<a href=\"/ships/%s/\"><span class=\"dim\">&lt;&lt;</span> BACK TO SHIP</a>\\n\\n\\n" "${ship}"
            cat "$auth"
            printf "</pre></div></body></html>"
          } >> "${author_html}"
          printf "\\n© %s <a href=\"%s\">%s</a>\\n" "$(date +%Y)" "/ships/${ship}/author.html" "$(head -n 1 "$auth")"
        else
          printf "\\n© %s %s\\n" "$(date +%Y)" "$(stat -c %U "${gopher_dir}/${ship}")"
        fi

        # License
        lic="/var/gopher/${ship}/LICENSE"
        if [ -f "$lic" ]; then
          cp "$lic" "${html_dir}/ships/${ship}/LICENSE.txt"
          printf "<a href=\"%s\">%s</a>" "/ships/${ship}/LICENSE.txt" "$(head -n 1 "$lic")"
        else
          printf "All rights reserved.\\n"
        fi
        printf "</pre></div></body></html>"
      } >> "${ship_html}"
    fi
  done
  # Footer
  {
    printf "</div>\\n"
    printf "</body>\\n"
    printf "</html>"
  } >> "${ships_html}"

  # Print error page
  cat "$web_header_html" > "${error_html}"
  {
    cat "$web_styles_html"
    printf "</head><body><div class=\"page-wrapper\"><pre class=\"inner-wrapper\"><a href=\"/\"><span class=\"dim\">&lt;&lt;</span> BACK TO RELAY ONE</a>"
    printf "\\n\\n\\nERROR. TRANSMISSION NOT FOUND.</pre></div></body></html>"
  } >> "${error_html}"

  # Print How to Join  page
  cat "$web_header_html" > "${join_html}"
  {
    printf "<title>Cosmic Voyage - How to Join</title>"
    printf "<link rel=\"canonical\" href=\"https://cosmic.voyage/join.html\">"
    cat "$web_styles_html"
    printf "</head>"
    printf "<body>"
    printf "<div class=\"page-wrapper\">"
    printf "<pre class=\"inner-wrapper\">"
    printf "<a href=\"/\"><span class=\"dim\">&lt;&lt;</span> BACK TO COSMIC VOYAGE</a>\\n\\n\\n"
    cat "/var/gopher/join.txt"
    printf "</pre></div></body></html>"
  } >> "${join_html}"

  # copy favicon
  cp "/var/cosmic/favicons/"* "${html_dir}"

  # copy cosmic banner
  cp "/var/cosmic/files/cosmicbanner.png" "${html_dir}"
  cp "/var/cosmic/files/paper.png" "${html_dir}"

  # generate tilde.json
  printf '{"name": "cosmic.voyage", "url": "https://cosmic.voyage", "signup_url": "https://cosmic.voyage/join.html", "user_count": %s, "want_users": true, "admin_email": "register@cosmic.voyage", "description": "Cosmic Voyage is a public-access unix system and tilde community based around a collaborative science-fiction universe. Users write stories as the people aboard ships, colonies, and outposts, using the only remaining free, interconnected network that unites the dispersed peoples of the stars."}' "$(grep -E '1[0-9]{3}' "/etc/passwd" | grep -c 'home')" > "${html_dir}/tilde.json"

  # Let user's know it's done
  printf "Web and RSS rebuilt.\\n"
else
  exec sudo -u publish "$0" "$@"
fi
