#!/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-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGWS+930b8QdzbchGljt3KSljH9wRhYvht8srrtQHdzg 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
   --reset-appstore-account  Reset associated cloudron.io account
   --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,reset-appstore-account" -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 creationTime LIMIT 1" 2>/dev/null)
        admin_password=$(pwgen -1s 12)
        dashboard_domain=$(mysql -NB -uroot -ppassword -e "SELECT value FROM box.settings WHERE name='admin_fqdn'" 2>/dev/null)
        mysql -NB -uroot -ppassword -e "INSERT INTO box.settings (name, value) VALUES ('ghosts_config', '{\"${admin_username}\":\"${admin_password}\"}') ON DUPLICATE KEY UPDATE name='ghosts_config', value='{\"${admin_username}\":\"${admin_password}\"}'" 2>/dev/null
        echo "Login at https://${dashboard_domain} as ${admin_username} / ${admin_password} . This password may only be used once."
        exit 0
        ;;
    --reset-appstore-account)
        echo -e "This will reset the Cloudron.io account associated with this Cloudron. Once reset, you can re-login with a different account in the Cloudron Dashboard. See https://docs.cloudron.io/appstore/#change-account for more information.\n"
        read -e -p "Reset the Cloudron.io account? [y/N] " choice
        [[ "$choice" != [Yy]* ]] && exit 1
        mysql -uroot -ppassword -e "DELETE FROM box.settings WHERE name='cloudron_token';" 2>/dev/null
        dashboard_domain=$(mysql -NB -uroot -ppassword -e "SELECT value FROM box.settings WHERE name='admin_fqdn'" 2>/dev/null)
        echo "Account reset. Please re-login at https://${dashboard_domain}/#/appstore"
        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

if [[ "${enableSSH}" == "true" ]]; then
    ssh_port=$(cat /etc/ssh/sshd_config | grep "Port " | sed -e "s/.*Port //")

    ssh_user="cloudron-support"
    keys_file="/home/cloudron-support/.ssh/authorized_keys"

    echo -e $LINE"SSH"$LINE >> $OUT
    echo "Username: ${ssh_user}" >> $OUT
    echo "Port:     ${ssh_port}" >> $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"

    exit 0
fi

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

# clear file
rm -rf $OUT

echo -e $LINE"DASHBOARD DOMAIN"$LINE >> $OUT
mysql -NB -uroot -ppassword -e "SELECT value FROM box.settings WHERE name='admin_fqdn'" &>> $OUT 2>/dev/null || true

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"Interface Info"$LINE >> $OUT
ip addr &>> $OUT

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

echo "Done"

echo -n "Uploading information..."
paste_key=$(curl -X POST ${PASTEBIN}/documents --silent --data-binary "@$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}"
