#!/bin/bash

USER="unifi-protect"
GROUP="unifi-protect"
DB_NAME="unifi-protect"
DB_USER="unifi-protect"
PKG="unifi-protect"

mkdir -p "/var/log/$PKG"
chown -R "$USER:$GROUP" "/var/log/$PKG"

su postgres -c "createuser $DB_USER -d" || true

# Datbase used to be owned by postgres, reassign databse owner if needed.
if [ "$( psql -U postgres -tAc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" || echo '0')" = '1' ]
then
  echo "Database exists, checking ownership"
  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
    echo "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
else
  echo "Database does not exist"
fi

mkdir -p "$UFP_DATADIR" "$UFP_TMPFS_DIR" "$UFP_BACKUPS_DIR" "$UFP_BACKUPS_DIR_HD" "$UFP_SOCKETS_DIR"
chown -R "$USER:$GROUP" "$UFP_DATADIR" "$UFP_TMPFS_DIR" "$UFP_BACKUPS_DIR" "$UFP_BACKUPS_DIR_HD" "$UFP_SOCKETS_DIR"

mount -t tmpfs -o size=$UFP_TMPFS_SIZE tmpfs "$UFP_TMPFS_DIR" || true
