#!/usr/bin/env bash

SYSTEMCTL=$(command -v systemctl)

# create config dirs, no-op if exists
mkdir -p /etc/qbee/ppkeys

# copy ca cert in place
cp -a /opt/qbee/share/ssl/ca.cert /etc/qbee/ppkeys

# set permissions
chmod 700 /etc/qbee /etc/qbee/ppkeys
chmod 600 /etc/qbee/ppkeys/ca.cert

# do systemctl operations if applicable
if [[ -n $SYSTEMCTL ]]; then
  if [[ -d /run/systemd/system ]]; then
    systemctl daemon-reload
  fi
  systemctl enable qbee-agent
fi


# Check of systemctl is available on system
[[ -z $SYSTEMCTL ]] && exit 0

# Check if system is running systemd
[[ ! -d /run/systemd/system ]] && exit 0

# Only start the agent if config file is in place
if [[ ! -f /etc/qbee/qbee-agent.json ]]; then
  echo "Device seems to not have been bootstrapped. Please run 'qbee-agent bootstrap -k <bootstrap-key>' as root to bootstrap."
  exit 0
fi

# Do a non-blocking restart of qbee-agent in case upgrade is done through qbee-agent itself
systemctl --no-block restart qbee-agent
