# Get the current non-root user
CURRENT_USER=$(who | awk 'NR==1{print $1}')

# Executed after package installation
post_install() {
	# Check if Docker is installed
	if ! command -v docker >/dev/null 2>&1; then
		echo "The Docker package is not installed. Please install it before continuing."
		exit 1
	fi

	# Start the LAMP container using docker-compose
    echo "Starting the LAMP container..."

    # Expand $CURRENT_USER and execute docker-compose with eval
    eval "HOME=/home/$CURRENT_USER docker-compose -f /etc/docker-biglinux/lamp/docker-compose.yml up -d"
    
    # Symlink docker-compose.yml to Docker/LAMP folder
    echo "Creating symlink to docker-compose.yml..."
    ln -s /etc/docker-biglinux/lamp/docker-compose.yml /home/$CURRENT_USER/Docker/LAMP/docker-compose.yml
    
    # Copy file index.php to Docker/LAMP folder only if it doesn't exist
    cp -f /etc/docker-biglinux/lamp/index.php /home/$CURRENT_USER/Docker/LAMP/html/
        
    # Set the correct owner and group for the Docker folder and its contents
    echo "Setting correct permissions for Docker folder..."
    chown -R $CURRENT_USER:$CURRENT_USER /home/$CURRENT_USER/Docker/LAMP
}

# Upgrade package
post_upgrade() {
    # Copy file index.php to Docker/LAMP folder only if it doesn't exist
    if [ ! -f /home/$CURRENT_USER/Docker/LAMP/html/index.php ]; then
        echo "Copying index.php to Docker/LAMP folder..."
        cp -f /etc/docker-biglinux/lamp/index.php /home/$CURRENT_USER/Docker/LAMP/html/
    else
        echo "File index.php already exists, skipping copy..."
    fi
    
    # Set the correct owner and group for the Docker folder and its contents
    echo "Setting correct permissions for Docker folder..."
    chown -R $CURRENT_USER:$CURRENT_USER /home/$CURRENT_USER/Docker/LAMP
}

# Executed before package removal
pre_remove() {
	# Stop and remove the LAMP container
	echo "Stopping and removing the LAMP container..."
	docker-compose -f /etc/docker-biglinux/lamp/docker-compose.yml down
	
	# Remove symlink to docker-compose.yml in Docker/LAMP folder
    echo "Removing symbolic link to docker-compose.yml..."
    rm -f /home/$CURRENT_USER/Docker/LAMP/docker-compose.yml
}

# Executed after package removal
post_remove() {
	# Remove the Docker image
    echo "Removing the LAMP Docker image..."
    docker rmi mariadb:lts
    docker rmi php:apache
}
