#!/bin/sh

run_user=$(id -un)
if [ "$run_user" = "root" ] || [ "$run_user" = "publish" ]; then
  author_index="/var/www/authors/index.html"
  {
    printf "<!DOCTYPE html>\\n"
    printf "<html lang=\"en\">\\n"
    printf "  <head>\\n"
    printf "    <meta charset=utf-8>\\n"
    printf "    <meta http-equiv=X-UA-Compatible content=\"IE=edge\">\\n"
    printf "    <meta name=viewport content=\"shrink-to-fit=no,width=device-width,height=device-height,initial-scale=1,user-scalable=1\">\\n"
    printf "    <title>Cosmic Voyage - Authors</title>\\n"
    printf "    <link rel=\"stylesheet\" href=\"/styles.css\">\\n"
    printf "    <link rel=\"canonical\" href=\"https://authors.cosmic.voyage\">\\n"
    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.\">\\n"
    printf "    </head>\\n"
    printf "    <body>\\n"
    printf "    <div class=\"page-wrapper\">\\n"
    printf "<pre class=\"inner-wrapper\">\\n"
    printf "          _. _  __._ _ * _.  .  , _   . _. _  _\\n"
    printf "         (_.(_)_) [ | )|(_.   \/ (_)\_|(_](_](/,\\n"
    printf "                                    ._|   ._|\\n"
    printf "                        , .\\n"
    printf "                  _.. .-+-|_  _ ._ __\\n"
    printf "                 (_](_| | [ )(_)[ _)\\n"
    printf "\\n\\n"
  } > "${author_index}"

  web_paths="/home/*/public_html"
  for i in ${web_paths}; do
    if [ -d "$i" ]; then
      username="$(basename "$(dirname "$i")")"
      printf "* <a href=\"/~%s/\">~%s</a>\\n" "${username}" "${username}" >> "${author_index}"
    fi
  done

  {
    printf "</pre>\\n"
    printf "</body>\\n"
    printf "</html>"
  } >> "${author_index}"
else
  exec sudo -u publish "$0" "$@"
fi
