#!/bin/bash
# Ubuntu 22.04
# Instalacion de docker, netdata y actualizacion de puerto ssh

read -rp "Hostname: " hostname

hostname "$hostname"
echo "$hostname" > /etc/hostname

apt update && apt -y upgrade && apt -y install curl wget sudo nload htop;

# Descargar e instalar cloudpanel
curl -sS https://installer.cloudpanel.io/ce/v2/install.sh -o install.sh;
sudo DB_ENGINE=MARIADB_10.11 /bin/bash install.sh;

# Agregar autoupdate
mkdir /etc/clpc;
wget repo.zarat.dev/cloudpanel/clp-autoupdate.sh -O /etc/clpc/clp-autoupdate.sh;
chmod +x /etc/clpc/clp-autoupdate.sh;
#write out current crontab
crontab -l > mycron
echo "1 4 * * * /bin/bash /etc/clpc/clp-autoupdate.sh" >> mycron
#install new cron file
crontab mycron
rm mycron

# TODO: Agregar templates extras
clpctl vhost-template:add --name='Video' --file=https://repo.zarat.dev/cloudpanel/video.tpl

# Instalar extras:
apt -y install nginx-extras 

# Instalar Docker
apt-get update
apt-get -y install ca-certificates curl gnupg
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
source /etc/os-release
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu   $VERSION_CODENAME stable" > /etc/apt/sources.list.d/docker.list
apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin


# Instalar netdata
docker run -d --name=netdata \
  -p 19999:19999 \
  -v netdataconfig:/etc/netdata \
  -v netdatalib:/var/lib/netdata \
  -v netdatacache:/var/cache/netdata \
  -v /etc/passwd:/host/etc/passwd:ro \
  -v /etc/group:/host/etc/group:ro \
  -v /proc:/host/proc:ro \
  -v /sys:/host/sys:ro \
  -v /etc/os-release:/host/etc/os-release:ro \
  --restart unless-stopped \
  --cap-add SYS_PTRACE \
  --security-opt apparmor=unconfined \
  --hostname "$hostname" \
  netdata/netdata;

# SSH config:
wget repo.zarat.dev/sshd_config -O /etc/ssh/sshd_config;
ufw allow 20497/tcp
ufw allow 19999/tcp
service sshd restart


# Template IP
ip=$(ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}')

echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "The installation of CloudPanel is complete!"
echo ""
echo "CloudPanel can be accessed now: https://$ip:8443"
echo -e "Netdata: http://$ip:19999"
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "Abre puertos SSH y Netdata desde cloudpanel:"
echo ""
curl repo.zarat.dev/cloudpanel/fmin.txt;
echo ""
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
