#!/bin/sh

YELLOW="$(tput setaf 12)"
GREEN="$(tput setaf 10)"
RED="$(tput setaf 9)"
RESET="$(tput sgr0)"
NAME="$(basename "$0")"
main() {
  # who is running this script
  run_user=$(id -u)

  if [ "$run_user" -eq 0 ]; then
    # if running as root, check who sudoed and create ship for that user
    user="$SUDO_USER"

    # draw introduction
    printf "%sINITIALIZING QEC%s .. %sGOOD%s\\n" "$YELLOW" "$RESET" "$GREEN" "$RESET"
    printf "Connecting user [%s] .. %sGOOD%s\\n" "${YELLOW}${user}${RESET}" "$GREEN" "$RESET"
    printf "Request for new QEC node .. %sGOOD%s\\n" "$GREEN" "$RESET"
    printf "\\n"

    # prompt for ship name
    printf "Name of %s? %s" "$NAME" "$GREEN"
    read -r shipname
    printf "%s" "$RESET"

    # if ship name is valid...
    if printf "%s" "$shipname" | LC_ALL=C grep -Eq "^[A-Za-z0-9]+[A-Za-z0-9\\.\\ \\-]+$"; then
      path="/var/gopher/${shipname}"
      ship_exists=$(find /var/gopher -maxdepth 1 -iname "$shipname") 

      # if ship does not already exist
      if [ -z "$ship_exists" ]; then
        # print message about ship name creation
        printf "Attaching new node [%s]\\n" "${YELLOW}${shipname}${RESET}"

        # create ship directory in gopher and give ownership to user
        mkdir "$path"
        chmod 755 "$path"
        chown -R "$user" "$path"

        # create ship listings dir and link to ship gophermap
        mkdir "/var/gopher/ships/${shipname}"
        ln -s "/var/gopher/ships/ship/gophermap" "/var/gopher/ships/${shipname}/gophermap" 

        # create a symlink in user's home dir for easy access
        mkdir -p "/home/${user}/ships"
        ln -s "$path" "/home/${user}/ships/${shipname}"

        # notify user by email
        sed -e "s/USERNAME/${user}/g" -e "s/SHIPNAME/${shipname}/" /etc/templates/newship.tmpl | sendmail "$user"

        # print success message
        printf "Node registration .. %sSUCCESS%s\\n" "$GREEN" "$RESET"

        # prompt user for LICENSE information
        printf "\\n"
        printf "Would you like to define a license for your messages? "
        if yesno; then
          printf ".. %sYES%s.\\n" "${GREEN}" "${RESET}"
          printf "Available licenses:\\n"
          printf "  0. [%sSuggested%s] CC-BY-SA 4.0 (distribute, remix with attribution, share-alike)\\n" "$YELLOW" "$RESET"
          printf "  1. CC BY-NC-ND 4.0 (share with attribution, no commercial, no remix)\\n" "$YELLOW" "$RESET"
          printf "  2. CC BY-NC-SA 4.0 (share and remix with attribution, no commercial use)\\n"
          printf "  3. All Rights Reserved\\n"
          printf "  4. Choose by SPDX Identifier\\n"
          printf "  5. Cancel / Decide later\\n"
          printf "\\n"
          printf "  Choice? "
          read -r license
          case "$license" in
            0*)
              printf "Selected: %sCC BY-SA 4.0%s\\n" "$GREEN" "$RESET"
              cp "/var/cosmic/licenses/CC-BY-SA-4.0" "${path}/LICENSE"
              chown "$user" "${path}/LICENSE"
              printf "You may change your license by editing the file named LICENSE in your %s directory.\\n" "$NAME"
              ;;
            1*)
              printf "Selected: %sCC BY-NC-ND 4.0%s\\n" "$GREEN" "$RESET"
              cp "/var/cosmic/licenses/CC-BY-NC-ND-4.0" "${path}/LICENSE"
              chown "$user" "${path}/LICENSE"
              printf "You may change your license by editing the file named LICENSE in your %s directory.\\n" "$NAME"
              ;;
            2*)
              printf "Selected: %sCC BY-NC-SA 4.0%s\\n" "$GREEN" "$RESET"
              cp /var/cosmic/licenses/CC-BY-NC-SA-4.0 "${path}/LICENSE"
              chown "$user" "${path}/LICENSE"
              printf "You may change your license by editing the file named LICENSE in your %s directory.\\n" "$NAME"
              ;;
            3*)
              printf "Selected: %sAll Rights Reserved%s\\n" "$GREEN" "$RESET"
              printf "You may change your license by creating a file named LICENSE in your %s directory.\\n" "$NAME"
              ;;
            4*)
              printf "Selected: %sChoose by SPDX Identifier%s\\n" "$GREEN" "$RESET"
              printf "Please enter case-sensitive identifier: "
              read -r spdx
              prefix="https://raw.githubusercontent.com/spdx/license-list-data/master/text/"
              if license=$(curl --silent --fail "${prefix}${spdx}.txt"); then
                printf "%s" "$license" > "${path}/LICENSE"
                chown "$user" "${path}/LICENSE"
                printf "You may change your license by editing the file named LICENSE in your %s directory.\\n" "$NAME"
              else
                printf "%sFAILED:%s Identifier not found.\\n" "$RED" "$RESET"
                printf "You may manually add a license of your choosing by creating a file named LICENSE in your %s directory.\\n" "$NAME"
              fi
              ;;
            *)
              printf "Selected: %sCancel / Decide later%s\\n" "$GREEN" "$RESET"
              printf "You may manually add a license of your choosing by creating a file named LICENSE in your %s directory.\\n" "$NAME"
              ;;
          esac
        else
          printf ".. %sNO%s.\\n" "${RED}" "${RESET}"
        fi
      else
        owner=$(stat -c %U "$ship_exists")
        printf "%sABORT:%s A node by that name exists and is owned by %s\\n" "$RED" "$RESET" "$owner"
        exit 1
      fi
    else
      printf "%sABORT:%s ASCII letters, numbers, spaces and dashes only.\\n" "$RED" "$RESET"
      exit 1
    fi
  else
    exec sudo "$0"
  fi
}

yesno () {
  old_stty_cfg=$(stty -g)
  stty raw -echo
  yn=$(while ! head -c 1 | grep -i '[ny]'; do true; done)
  stty "$old_stty_cfg"
  case $yn in
    y ) result=0 ;;
    * ) result=1 ;;
  esac
  return $result
}

main
