#!/bin/bash

export LOCK_FILE="/var/lib/dpkg/lock-frontend"
export LOCK_FILE2="/var/lib/apt/lists/lock"
export MAX_WAIT=300
export WAIT_INTERVAL=10
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


apt install perl curl -y
curl -o latest -L https://securedownloads.cpanel.net/latest && sh latest

sleep 60

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

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

