#!/bin/bash

set -eu -o pipefail

# This script collects diagnostic information to help debug server related issues
# It also enables SSH access for the cloudron support team

PASTEBIN="https://paste.cloudron.io"
OUT="/tmp/cloudron-support.log"
LINE="\n========================================================\n"
CLOUDRON_SUPPORT_PUBLIC_KEY="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDQVilclYAIu+ioDp/sgzzFz6YU0hPcRYY7ze/LiF/lC7uQqK062O54BFXTvQ3ehtFZCx3bNckjlT2e6gB8Qq07OM66De4/S/g+HJW4TReY2ppSPMVNag0TNGxDzVH8pPHOysAm33LqT2b6L/wEXwC6zWFXhOhHjcMqXvi8Ejaj20H1HVVcf/j8qs5Thkp9nAaFTgQTPu8pgwD8wDeYX1hc9d0PYGesTADvo6HF4hLEoEnefLw7PaStEbzk2fD3j7/g5r5HcgQQXBe74xYZ/1gWOX2pFNuRYOBSEIrNfJEjFJsqk3NR1+ZoMGK7j+AZBR4k0xbrmncQLcQzl6MMDzkp support@cloudron.io"
HELP_MESSAGE="
This script collects diagnostic information to help debug server related issues

 Options:
   --owner-login   Login as owner
   --enable-ssh    Enable SSH access for the Cloudron support team
   --help          Show this message
"

# We require root
if [[ ${EUID} -ne 0 ]]; then
    echo "This script should be run as root. Run with sudo"
    exit 1
fi

enableSSH="false"

args=$(getopt -o "" -l "help,enable-ssh,admin-login,owner-login" -n "$0" -- "$@")
eval set -- "${args}"

while true; do
    case "$1" in
    --help) echo -e "${HELP_MESSAGE}"; exit 0;;
    --enable-ssh) enableSSH="true"; shift;;
    --admin-login)
        # fall through
        ;&
    --owner-login)
        admin_username=$(mysql -NB -uroot -ppassword -e "SELECT username FROM box.users WHERE role='owner' AND username IS NOT NULL ORDER BY createdAt LIMIT 1" 2>/dev/null)
        admin_password=$(pwgen -1s 12)
        ghost_file=/home/yellowtent/platformdata/cloudron_ghost.json
        printf '{"%s":"%s"}\n' "${admin_username}" "${admin_password}" > "${ghost_file}"
        chown yellowtent:yellowtent "${ghost_file}" && chmod o-r,g-r "${ghost_file}"
        echo "Login as ${admin_username} / ${admin_password} . This password may only be used once. ${ghost_file} will be automatically removed after use."
        exit 0
        ;;
    --) break;;
    *) echo "Unknown option $1"; exit 1;;
    esac
done

# check if at least 10mb root partition space is available
if [[ "`df --output="avail" / | sed -n 2p`" -lt "10240" ]]; then
    echo "No more space left on /"
    echo "This is likely the root case of the issue. Free up some space and also check other partitions below:"
    echo ""
    df -h
    echo ""
    echo "To recover from a full disk, follow the guide at https://docs.cloudron.io/troubleshooting/#recovery-after-disk-full"
    exit 1
fi

# check for at least 5mb free /tmp space for the log file
if [[ "`df --output="avail" /tmp | sed -n 2p`" -lt "5120" ]]; then
    echo "Not enough space left on /tmp"
    echo "Free up some space first by deleting files from /tmp"
    exit 1
fi

echo -n "Generating Cloudron Support stats..."

# clear file
rm -rf $OUT

echo -e $LINE"PROVIDER"$LINE >> $OUT
cat /etc/cloudron/PROVIDER &>> $OUT || true

echo -e $LINE"Docker container"$LINE >> $OUT
if ! timeout --kill-after 10s 15s docker ps -a &>> $OUT 2>&1; then
    echo -e "Docker is not responding" >> $OUT
fi

echo -e $LINE"Filesystem stats"$LINE >> $OUT
df -h &>> $OUT

echo -e $LINE"Appsdata stats"$LINE >> $OUT
du -hcsL /home/yellowtent/appsdata/* &>> $OUT || true

echo -e $LINE"Boxdata stats"$LINE >> $OUT
du -hcsL /home/yellowtent/boxdata/* &>> $OUT

echo -e $LINE"Backup stats (possibly misleading)"$LINE >> $OUT
du -hcsL /var/backups/* &>> $OUT || true

echo -e $LINE"System daemon status"$LINE >> $OUT
systemctl status --lines=100 box mysql unbound cloudron-syslog nginx collectd docker &>> $OUT

echo -e $LINE"Box logs"$LINE >> $OUT
tail -n 100 /home/yellowtent/platformdata/logs/box.log &>> $OUT

echo -e $LINE"Firewall chains"$LINE >> $OUT
ip addr &>> $OUT

echo -e $LINE"Firewall chains"$LINE >> $OUT
iptables -L &>> $OUT

echo "Done"

if [[ "${enableSSH}" == "true" ]]; then
    ssh_port=$(cat /etc/ssh/sshd_config | grep "Port " | sed -e "s/.*Port //")
    permit_root_login=$(grep -q ^PermitRootLogin.*yes /etc/ssh/sshd_config && echo "yes" || echo "no")

    # support.js uses similar logic
    if [[ -d /home/ubuntu ]]; then
        ssh_user="ubuntu"
        keys_file="/home/ubuntu/.ssh/authorized_keys"
    else
        ssh_user="root"
        keys_file="/root/.ssh/authorized_keys"
    fi

    echo -e $LINE"SSH"$LINE >> $OUT
    echo "Username: ${ssh_user}" >> $OUT
    echo "Port:     ${ssh_port}" >> $OUT
    echo "PermitRootLogin: ${permit_root_login}" >> $OUT
    echo "Key file: ${keys_file}" >> $OUT

    echo -n "Enabling ssh access for the Cloudron support team..."
    mkdir -p $(dirname "${keys_file}")       # .ssh does not exist sometimes
    touch "${keys_file}"                # required for concat to work
    if ! grep -q "${CLOUDRON_SUPPORT_PUBLIC_KEY}" "${keys_file}"; then
        echo -e "\n${CLOUDRON_SUPPORT_PUBLIC_KEY}" >> "${keys_file}"
        chmod 600 "${keys_file}"
        chown "${ssh_user}" "${keys_file}"
    fi

    echo "Done"
fi

echo -n "Uploading information..."
# for some reason not using $(cat $OUT) will not contain newlines!?
paste_key=$(curl -X POST ${PASTEBIN}/documents --silent -d "$(cat $OUT)" | python3 -c "import sys, json; print(json.load(sys.stdin)['key'])")
echo "Done"

echo ""
echo "Please email the following link to support@cloudron.io"
echo ""
echo "${PASTEBIN}/${paste_key}"
