#!/usr/bin/env bash
clear
# Bash script: Markdown app + Nginx setup with colored step messages
# - Orange when Processing, Green when Success, Red when Failed
# - Blank line and 2s delay between each message
# - Checks each command's exit status before reporting Success/Failed
# - Prints a final message with the host's IP address
# - Filename: install-markdown.sh
# Tested on Debian/Ubuntu-family systems

# ---------- Colors ----------
ORANGE='\e[38;5;208m'   # 256-color "DarkOrange" (index 208)
GREEN='\e[32m'
RED='\e[31m'
NC='\e[0m'

# ---------- Messaging helpers ----------
msg() {
  # $1 = color, $2 = text
  printf "%b%s%b\n\n" "$1" "$2" "$NC"
}

run() {
  # $1 = description (shown to user)
  # $2... = command and args
  local desc="$1"
  shift
  msg "$ORANGE" "Processing: $desc..."
  sleep 2
  if "$@"; then
    msg "$GREEN" "Success: $desc."
  else
    local rc=$?
    msg "$RED" "Failed: $desc (exit code $rc)."
  fi
}

# ---------- Privilege check ----------
msg "$ORANGE" "Processing: Checking for root privileges..."
if [ "$(id -u)" -ne 0 ]; then
  msg "$RED" "Failed: This script must be run as root. Try: sudo bash $0"
  exit 1
else
  msg "$GREEN" "Success: Running as root."
fi

# ---------- Non-interactive apt ----------
export DEBIAN_FRONTEND=noninteractive

# ---------- Steps ----------
run "Update APT package index" apt update
run "Install Nginx" apt install -y nginx
run "Enable and start Nginx" systemctl enable --now nginx

run "Create app directory" mkdir -p /var/www/markdown-app
run "Set ownership for app directory" chown -R www-data:www-data /var/www/markdown-app

# Download index.html.bak and deploy as index.html
URL="https://docs.greenhome.stream/attachments/43"
TMP="/tmp/index.html.bak"

msg "$ORANGE" "Processing: Downloading index.html.bak..."
if command -v curl >/dev/null 2>&1; then
  if curl -fsSL -o "$TMP" "$URL"; then
    msg "$GREEN" "Success: Downloaded index.html.bak."
  else
    msg "$RED" "Failed: Downloading index.html.bak."
  fi
elif command -v wget >/dev/null 2>&1; then
  if wget -qO "$TMP" "$URL"; then
    msg "$GREEN" "Success: Downloaded index.html.bak."
  else
    msg "$RED" "Failed: Downloading index.html.bak."
  fi
else
  msg "$RED" "Failed: Neither curl nor wget found for download."
fi

msg "$ORANGE" "Processing: Renaming and moving index.html to /var/www/markdown-app/..."
if [ -s "$TMP" ]; then
  # install sets owner/perm atomically
  if install -o www-data -g www-data -m 0644 "$TMP" /var/www/markdown-app/index.html; then
    msg "$GREEN" "Success: Deployed /var/www/markdown-app/index.html."
  else
    msg "$RED" "Failed: Deploying index.html to /var/www/markdown-app/."
  fi
else
  msg "$RED" "Failed: Downloaded file missing or empty; cannot deploy index.html."
fi

# Write Nginx server block
NGINX_CONF_PATH="/etc/nginx/sites-available/markdown-app"
read -r -d '' NGINX_CONF_CONTENT <<'EOF'
server {
    listen 80;
    server_name _;
    root /var/www/markdown-app;
    index index.html;
    location / {
        try_files $uri $uri/ =404;
    }
    access_log /var/log/nginx/markdown-app.access.log;
    error_log  /var/log/nginx/markdown-app.error.log;
}
EOF

msg "$ORANGE" "Processing: Writing Nginx site configuration (/etc/nginx/sites-available/markdown-app)..."
if printf '%s\n' "$NGINX_CONF_CONTENT" > "$NGINX_CONF_PATH"; then
  msg "$GREEN" "Success: Wrote Nginx site configuration."
else
  msg "$RED" "Failed: Writing Nginx site configuration."
fi

# Enable site, remove default, test and reload
run "Enable site via symlink" ln -sf /etc/nginx/sites-available/markdown-app /etc/nginx/sites-enabled/markdown-app
run "Remove default site" rm -f /etc/nginx/sites-enabled/default
run "Test Nginx configuration" nginx -t
run "Reload Nginx" systemctl reload nginx

# Determine host IPv4 address
# 1) Try hostname -I (first IPv4), 2) fallback to routing-derived source IP
msg "$ORANGE" "Processing: Detecting host IPv4 address..."
IP="$(hostname -I 2>/dev/null | awk '{for(i=1;i<=NF;i++){if($i ~ /^[0-9.]+$/){print $i; exit}}}')"
if [ -z "$IP" ]; then
  IP="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '/src/ {for (i=1;i<=NF;i++){if ($i=="src"){print $(i+1); exit}}}')"
fi

if [ -n "$IP" ]; then
  msg "$GREEN" "Success: Detected host IP: $IP"
else
  msg "$RED" "Failed: Could not determine host IP address."
fi

# Final message
msg "$GREEN" "You are DONE."
msg "$GREEN" "You can visit your Markdown <-> HTML + WYSIWYG -> Markdown/HTML Web App at this address :"
msg "$GREEN" "                                    http://$IP"

# Leave an empty line and exit
printf "\n"
exit 0
