#!/bin/bash

set -e
shopt -s nullglob

root=/ngcp-fallback
cfgdir=${root}/etc/ngcp-config
oldssl=${cfgdir}/ssl
newssl=${cfgdir}/shared-files/ssl

if ! [ -d ${newssl} ]; then
  mkdir -p ${newssl}
  chown root:ssl-cert ${newssl}
  chmod 0750 ${newssl}
fi

if [ -d ${oldssl} ]; then
  for cert in "${oldssl}"/*; do
    # Skip files owned by packages, as they need to move these themselves.
    if chroot ${root} dpkg-query --search "${cert#"${root}"}" >/dev/null 2>&1; then
      continue
    fi

    mv "${cert}" ${newssl}/
  done

  rmdir --ignore-fail-on-non-empty ${oldssl}
fi
