#!/usr/bin/env bash

set -e
SRC="/usr/local/src"

if [ "$(id -u)" -eq 0 ]; then
    echo "You are root."
else
    echo -e "\n==============================[ERROR]=================================\n  Please run this script as root!!!\n"
    exit 1
fi

if [ ! -d ${SRC}/portainer_uni ]; then
  mkdir -p ${SRC}/portainer_uni
fi

# Wait for any existing apt/dpkg lock to be released
wait_for_apt_lock() {
  echo "Checking for APT lock..."
  while fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1 || \
        fuser /var/lib/apt/lists/lock >/dev/null 2>&1 || \
        fuser /var/cache/apt/archives/lock >/dev/null 2>&1; do
    echo "APT is locked by another process. Waiting..."
    sleep 5
  done
  echo "APT lock released. Continuing..."
}

# Check if htpasswd is installed
if command -v htpasswd &> /dev/null; then
  echo "Necessary utility is already installed."
else
  wait_for_apt_lock
  apt-get update
  apt-get install ca-certificates curl wget apache2-utils -y
fi

if command -v docker &> /dev/null; then
  echo "Docker is already installed."
else
  curl -fsSL https://get.docker.com -o ${SRC}/portainer_uni/install-docker.sh
  sh ${SRC}/portainer_uni/install-docker.sh
fi

TEMPLATE_URL="https://screen.unihost.com/portainer/templates.json"

# Parse arguments
while getopts "d" opt; do
  case ${opt} in
    d)
      TEMPLATE_URL="https://screen.unihost.com/portainer/dev/templates.json"
      ;;
    *)
      echo "Usage: $0 [-d]"
      exit 1
      ;;
  esac
done

# Generate random pass
RANDOMPW=$(openssl rand -hex 16)
#echo "Login: admin\nPassword: $RANDOMPW"
PORTAINER_HASH=$(htpasswd -nb -B admin "$RANDOMPW" | cut -d ":" -f 2 | sed 's/\$/\$\$/g')


cat << EOF > ${SRC}/portainer_uni/docker-compose-portainer.yaml
networks:
  web:
    external: true

services:
  portainer-uni:
    container_name: portainer-uni
    image: portainer/portainer-ce:lts
    ports:
      - "9443:9443/tcp"
    volumes:
      - '/var/run/docker.sock:/var/run/docker.sock'
      - 'data:/data'
      - '/etc/localtime:/etc/localtime'
      - '/etc/timezone:/etc/timezone'
    labels:
      hide: "true"
    command: >
      '--admin-password=${PORTAINER_HASH}'
      '--templates=${TEMPLATE_URL}'
    restart: always
    networks:
      - web

volumes:
    data:
EOF

# Check if the container portainer-uni exists (running or stopped)
if [ -f ${SRC}/portainer_uni/docker-compose-portainer.yaml ]; then
  if ! docker ps -a --format '{{.Names}}' | grep -wq 'portainer-uni'; then
    echo "Starting docker-compose..."
    docker network create --driver bridge --attachable web
    docker network create --driver bridge --attachable databases
    docker compose -f ${SRC}/portainer_uni/docker-compose-portainer.yaml up -d
  else
    echo -e "\n\tContainer 'portainer-uni' already exists. Skipping docker-compose up.\n"
    exit 1
  fi
else
  echo "===Compose file does not exist."
fi

CONTAINER_NAME="portainer-uni"
SERVER_IP=$(ip route get 1.1.1.1 | awk '{print $7; exit}')

# Wait until the container is running with spinner animation
echo -n "Waiting for container '$CONTAINER_NAME' to be up... "

spinner='|/-\\'
i=0
while [[ "$(docker inspect -f '{{.State.Running}}' $CONTAINER_NAME 2>/dev/null)" != "true" ]]; do
  i=$(( (i+1) %4 ))
  printf "\b${spinner:$i:1}"
  sleep 0.2
done

clear

echo -e "\n=============== Instalation Complite !!!=================="

cat << EOF > /root/.portainer-info.sh
#!/bin/bash
echo -e "==========================================================\n"
echo -e "\tPortainer URL - https://${SERVER_IP}:9443\n"
echo -e "\tUser - admin\n\tPassword - ${RANDOMPW}\n"
echo -e "=========================================================="
EOF

chmod 750 /root/.portainer-info.sh

cat << 'EOF' >> /root/.bash_profile
if [ "$USER" = "root" ]; then
  if [ -f ~/.portainer-info.sh ]; then
    . ~/.portainer-info.sh
  fi
fi
EOF

/root/.portainer-info.sh
