#!/bin/bash

export LOCK_FILE="/var/lib/dpkg/lock-frontend"
export LOCK_FILE2="/var/lib/apt/lists/lock"
export WAIT_INTERVAL=5
export MAX_WAIT=300
export ELAPSED=0

if systemctl is-active --quiet unattended-upgrades; then
    systemctl stop unattended-upgrades
fi

while fuser $LOCK_FILE $LOCK_FILE2 >/dev/null 2>&1; do
    sleep $WAIT_INTERVAL
    ELAPSED=$((ELAPSED + WAIT_INTERVAL))
    if [ $ELAPSED -ge $MAX_WAIT ]; then
        PIDS=$(fuser $LOCK_FILE $LOCK_FILE2 2>/dev/null)
        if [ -n "$PIDS" ]; then
            kill -9 $PIDS
        fi
        dpkg --configure -a
        break
    fi
done

rm -f /var/lib/apt/lists/lock
rm -f /var/cache/apt/archives/lock
rm -f /var/lib/dpkg/lock*
dpkg --configure -a

apt update -y

curl -sS https://installer.cloudpanel.io/ce/v2/install.sh -o /tmp/install.sh 
echo "2aefee646f988877a31198e0d84ed30e2ef7a454857b606608a1f0b8eb6ec6b6 /tmp/install.sh" | sha256sum -c &>/dev/null
DB_ENGINE=MYSQL_8.0 bash /tmp/install.sh


sed -i 's/^\(\s*\)#\?listen\s\+\(\[::\]:\)\?8443\s\+ssl\s\+http2;/\1listen \28443 ssl;/g' /home/clp/services/nginx/sites-enabled/cloudpanel.conf

systemctl restart clp-nginx.service

HTTP_CODE=$(curl -o /dev/null -s -w "%{http_code}\n" http://localhost:8443 -kL)

if [ "$HTTP_CODE" -eq 200 ]; then
    echo "CloudPanel install success."
    exit 0
else
    echo "CloudPanel install failed."
    exit 1
fi

