#!/bin/bash
#Manages an /etc/changelog

# Immediately attempt to read from named pipe
# And store the piped content if provided
[[ -p /proc/self/fd/0 ]] && export STDIN=$( cat  )
# And then force the input to be from terminal
exec 0</dev/tty

# Defining some path variables
APP_PATH=$( cd $(dirname ${BASH_SOURCE[0]}) && pwd )
APP_NAME=$( basename ${BASH_SOURCE[0]})




# %CONFIG% This comment is used to build custom scripts
CHANGELOG=/etc/changelog
CHANGELOG_SERVER=https://changelog.tmplab.org
CHANGELOG_AUTH_KEY=ZZe1CGpWNLj7qEOMmBiXalZY7uV1
HASTEBIN_SERVER=https://paste.interhacker.space
[[ -f "$APP_PATH/config.sh" ]] && source "$APP_PATH/config.sh"

# Sanity check on changelog file
[[ -z "$CHANGELOG" ]] && CHANGELOG="/etc/Changelog"
[[ -f "$CHANGELOG" ]] && [[ ! -w "$CHANGELOG" ]] && RUN_SUDO=1
[[ ! -f "$CHANGELOG" ]] && ! touch /etc/changelog &>/dev/null && RUN_SUDO=1
[[ $RUN_SUDO -eq 1 ]] && {
    echo -e "\nYou cannot write to $CHANGELOG... This doesn't look serious!\n"
    read -e -i y -n 1 -p "Run as sudo [Yn]? : "
    [[ "Y" == ${REPLY^} ]] && sudo -E "$APP_PATH/$APP_NAME" && exit 0
}

# functions
msg(){ echo -e "$@"; }
panic(){ msg "${@} Exiting."; exit 1;}
ENTRY_FILE=$(mktemp)

# This is the main function
change(){
  TMP="$1"
  while true ; do
    echo -e "\nType the nature of the change.\nExample: > mysql: do not start on boot\n"
    read -e -p "> " SUB
    echo -e "* $SUB" >> $TMP
    echo -e "\nTime for some details."

    for (( ; ; )); do
      echo "Select number or x to quit"
      for (( i=0; i<${#PLUGIN_CONTENT_MENU[@]}; i++)) ; do
        echo "$i)  ${PLUGIN_CONTENT_MENU[$i]}"
      done
      echo "x)  No more details."
      read -e -n 1 -p "Your choice? :" REPLY
      if [[ "x" == ${REPLY,,} ]]; then
        break
      elif [[ -z "${PLUGIN_CONTENT[$REPLY]}" ]] ; then
        echo "Unknown Key."
      else
        ${PLUGIN_CONTENT[$REPLY]} $TMP
      fi
    done
    read -e -i "n" -p "Another section? [yN]:" END
    [[ "${END^^}" == "N" ]] && break
  done
}

template(){
FILE="$1"
cat << HEREDOC

$(date "+%Y-%m-%d %H:%M") $CHANGELOG_USERNAME
$( cat "$FILE" |sed 's/^/    /' )
HEREDOC
}

hookContentComment(){
  [[ -z "$1" ]] && echo "Enter a simple comment. Ex: systemctl disable nginx" && return
  TMP="$1"
  read -e -p "Your comment: " CONTENT
  echo "$CONTENT" >> $TMP
}

hookOutputFile(){
  [[ -z "$1" ]] && echo "Writing a local changelog entry to $CHANGELOG" && return
  local TMP=$(mktemp)
  SOURCE="$1"
  template "$SOURCE" > "$TMP"
  [[ -f "$CHANGELOG" ]] && cat /etc/changelog >> "$TMP"
  cat "$TMP" > $CHANGELOG
  rm -f "$TMP"

}


# Build the hook content menu
PLUGIN_CONTENT+=("hookContentComment")
declare -a PLUGIN_CONTENT_MENU

# Build the hook content menu
PLUGIN_OUTPUT+=("hookOutputFile")
declare -a PLUGIN_OUTPUT_MENU

# %PLUGIN% This comment is used to build custom scripts
# Add a content line by decorating the input with triple backticks ```
PLUGIN_CONTENT+=( hookContentCmd )
hookContentCmd(){
  [[ -z "$1" ]] && echo "Add a shell command line" && return
  TMP="$1"
  read -e -p "Command line? " CMD
  [[ -z "$CMD" ]] && panic "Not a valid content" && return
  echo "\`\`\`$CMD\`\`\`" >> $TMP
}

# Adds a line by sending a file to a hastebin server
# and then print a "/a/file/name https://haste.bin/urlurlurl" line
# Requires an environmental variable to work
# example HASTEBIN_SERVER=https://paste.interhacker.space
PLUGIN_CONTENT+=( hookContentHastebin )
hookContentHastebin(){
  [[ -z "$1" ]] && echo "Store a file by name in pastebin" && return
  [[ -z "$HASTEBIN_SERVER" ]] && echo "Missing HASTEBIN_SERVER variable. Exiting." && return
  TMP="$1"
  read -e -p "File location? " FILE
  [[ ! -f $FILE ]] && panic "Not a valid file" && return
  URL=$( curl -X POST -s -d "$(cat "$FILE" )" "$HASTEBIN_SERVER/documents" |  awk -F '"' '{print "'$HASTEBIN_SERVER'/raw/"$4}'; )
  echo "$FILE: $URL" >> $TMP
}

# Sends the changelog information to a changelog server
# see https://git.interhacker.space/alban/changelog-server
# Requires environmental variables to work
# CHANGELOG_SERVER
# CHANGELOG_AUTH_KEY
PLUGIN_OUTPUT+=( hookOutputChangelogServer )
hookOutputChangelogServer(){
  [[ -z "$1" ]] && echo "Sending changelog to remote server" && return
  [[ -z "$CHANGELOG_SERVER" ]] && echo "Missing CHANGELOG_SERVER variable. Exiting." && return
  [[ -z "$CHANGELOG_AUTH_KEY" ]] && echo "Missing CHANGELOG_AUTH_KEY variable. Exiting." && return
  CONTENT=$(jq -aRs . $1|tr '"' '\"')
  PAYLOAD="{\"author\":\"$CHANGELOG_USERNAME\",\"server\":\"$(hostname -f)\",\"content\":${CONTENT}}"
  URL=$( curl -X POST -H "AuthorizationToken: $CHANGELOG_AUTH_KEY" -H "Content-Type: application/json" -s -d "${PAYLOAD}" "$CHANGELOG_SERVER/changelog/_doc"; )
  [[ 0 -ne $? ]] && echo "Failed to upload the changelog..." && return
  echo "$FILE: $URL" >> $TMP
}
[[ -d "$APP_PATH/plugins-enabled" ]] && [[ -n "$APP_PATH/plugins-enabled/*" ]] && for plugin in "$APP_PATH"/plugins-enabled/*; do source $plugin; done

for (( i = 0; i < ${#PLUGIN_OUTPUT[@]} ; i++ )); do
  TXT=$( ${PLUGIN_OUTPUT[$i]} )
  PLUGIN_OUTPUT_MENU+=("$( ${PLUGIN_OUTPUT[$i]} )")
done
for (( i = 0; i < ${#PLUGIN_CONTENT[@]} ; i++ )); do
  TXT=$( ${PLUGIN_CONTENT[$i]} )
  PLUGIN_CONTENT_MENU+=("$( ${PLUGIN_CONTENT[$i]} )")
done


# Exec

echo -e "\nWelcome to Serious Changelogs Inc. Do you have something for me?\n"
# set environment variables
[[ -z "$CHANGELOG_USERNAME" ]] && read -e -p "Your name?  " NAME&& read -e -p "Your email? " EMAIL && CHANGELOG_USERNAME="${NAME^}  <$EMAIL>" && echo "export CHANGELOG_USERNAME=\"$CHANGELOG_USERNAME\""
[[ "  <>" == "$CHANGELOG_USERNAME" ]] && panic "srs.ly?"

# check changelog exists
[[ ! -f "$CHANGELOG" ]] && template "* Changelog: Added $CHANGELOG file\nIt was not serious. Fixed!\n\n" > "$CHANGELOG"

# Detect piped content
if [[ -n "$STDIN" ]] ; then
    echo -e "$STDIN" > $ENTRY_FILE

#OR enter interactive mode
else
    change "$ENTRY_FILE"
fi

# confirm the output
echo -e "\nHere is the content you are about to add:\n\n$(cat $ENTRY_FILE)\n"
read -e -p "OK? [Yn]: " -i y RETURN
[[ "N" == ${RETURN^^} ]] && exit 1

# Send data to outputs
for (( i=0; i<${#PLUGIN_OUTPUT_MENU[@]}; i++)) ; do
  echo "${PLUGIN_OUTPUT_MENU[$i]}"
  ${PLUGIN_OUTPUT[$i]} $ENTRY_FILE
done

rm "$ENTRY_FILE"
