#!/bin/bash

format_date() {
  date -u +"%Y-%m-%d %H:%M:%S"
}

log_line() {
  echo "$(format_date) pre-start --> $1"
}

# logfile cleanup in case of runaway logs
SIZE_LIMIT=$((100 * 1024 * 1024)) # 100 MB
MAIN_LOG_FILE_PATH="/var/log/unifi-talk-relay/unifi-talk-relay.log"
MAIN_LOG_FILE_SIZE=$(stat -c%s "$MAIN_LOG_FILE_PATH")

# check if logs exceed limit, truncate
if [[ -f "$MAIN_LOG_FILE_PATH" && $MAIN_LOG_FILE_SIZE -gt $SIZE_LIMIT ]]; then
  truncate -s 0 "$MAIN_LOG_FILE_PATH"
  log_line "truncated '$MAIN_LOG_FILE_PATH' (size: $((MAIN_LOG_FILE_SIZE / 1024 / 1024)) MB)"
fi

log_line "starting pre-start script"

USER="unifi-talk-relay"
GROUP="unifi-talk-relay"
DB_NAME="unifi-talk-relay"
DB_USER="unifi-talk-relay"
PKG="unifi-talk-relay"
LOGROTATE="/etc/logrotate.d/$PKG"
mkdir -p "/usr/share/$PKG/app/runtime"
mkdir -p "/var/log/$PKG"
chown -R "$USER:$GROUP" "/var/log/$PKG" "/usr/share/$PKG/app/runtime"

log_line "creating db user"
psql -U postgres <<-EOSQL
  CREATE USER "${DB_USER}";
  CREATE DATABASE "${DB_NAME}";
EOSQL

# Datbase used to be owned by postgres, reassign databse owner if needed.
if [ "$( psql -U postgres -tAc "SELECT pg_catalog.pg_get_userbyid(d.datdba) FROM pg_catalog.pg_database d WHERE d.datname = '$DB_NAME'" )" = $DB_NAME ]
then
  log_line "Database is already owned by $DB_USER"
else
  psql -U postgres -c "ALTER DATABASE \"$DB_NAME\" OWNER TO \"$DB_USER\""
  psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE \"$DB_NAME\" to \"$DB_USER\""
  psql -U postgres -c "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO \"$DB_USER\"" $DB_NAME
  psql -U postgres -c "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO \"$DB_USER\"" $DB_NAME
  for tbl in `psql -U postgres -qAt -c "select tablename from pg_tables where schemaname = 'public';" $DB_NAME` ; do  psql -U postgres -c "alter table \"$tbl\" owner to \"$DB_USER\"" $DB_NAME; done
  for tbl in `psql -U postgres -qAt -c "select sequence_name from information_schema.sequences where sequence_schema = 'public';" $DB_NAME` ; do  psql -U postgres -c "alter table \"$tbl\" owner to \"$DB_USER\"" $DB_NAME; done
  for tbl in `psql -U postgres -qAt -c "select table_name from information_schema.views where table_schema = 'public';" $DB_NAME` ; do  psql -U postgres -c "alter table \"$tbl\" owner to \"$DB_USER\"" $DB_NAME; done
fi

log_line "setting logrotate config"
if [ ! -f ${LOGROTATE} ]; then
cat << EOF > ${LOGROTATE}
/var/log/unifi-talk-relay/*.log {
         maxsize 10M
         rotate 5
         copytruncate
         compress
         notifempty
         missingok
         su root root
}
EOF
fi

log_line "creating internal directories"
for dir in "$UFT_INTERNAL_DIR" "$UFT_INTERNAL_DIR/contacts" "$UFT_INTERNAL_DIR/config"
do
    mkdir -p ${dir} || true
done

is_link() {
  [ -L "$1" ] && [ -e "$1" ] && return
  false
}

log_line "creating external directories"
if mountpoint -q /srv || is_link /srv; then
  for dir in "$UFT_EXTERNAL_DIR/contacts"
  do
      mkdir -p ${dir} || true
  done
  chown -R "$USER:${GROUP}" "$UFT_EXTERNAL_DIR"  || true
  chmod -R 770 "$UFT_EXTERNAL_DIR"  || true
fi

log_line "creating other directories"
for dir in "$UFT_EMMC_TMP_DIR"
do
    mkdir -p ${dir} || true
done

chown -R "$USER:${GROUP}" "$UFT_INTERNAL_DIR" "$UFT_EMMC_TMP_DIR"  || true
chmod -R 770 "$UFT_INTERNAL_DIR"  || true

ln -sf /usr/share/$PKG/app/node_modules/@babel/cli/bin/babel.js /usr/share/$PKG/app/node_modules/.bin/babel

log_line "pre-start script done"
