#!/bin/sh -e

DB_NAME=mibew
DB_USER=mibew
DB_PASS=$(mcookie)

ADMIN_NAME=admin
ADMIN_PASS=turnkey

SRC=/usr/local/src
WEBROOT=/var/www/mibew

# unpack and set permissions
mkdir -p "$(dirname "$WEBROOT")"
unzip "$SRC/mibew.zip" -d "$(dirname "$WEBROOT")"
rm "$SRC/mibew.zip"
chown -R root:root "$WEBROOT"
chown -R www-data:www-data "$WEBROOT/files/avatar" "$WEBROOT/cache"

# Mibew uses 0 for an ungrouped thread, while its schema represents an absent
# group with NULL. Current MariaDB enforces the declared foreign key.
THREAD_CLASS="$WEBROOT/libs/classes/Mibew/Thread.php"
test "$(grep -Fc "':group_id' => \$this->groupId," "$THREAD_CLASS")" -eq 2
sed -i "s/':group_id' => \$this->groupId,/':group_id' => \$this->groupId ?: null,/" \
    "$THREAD_CLASS"

# remove unrequired webcp icons (all except those named)
cd /var/www/images
find . -type f ! -name "adminer.png" ! -name "shell.png" ! -name "tab.png" ! -name "webmin.png" -delete

# setup tkl-webcp
mkdir -p "$WEBROOT/cp"
mv /var/www/index.php "$WEBROOT/cp"
mv /var/www/js "$WEBROOT/cp"
mv /var/www/css "$WEBROOT/cp"
mv /var/www/images "$WEBROOT/cp"
ln -s "$WEBROOT/cp" "$WEBROOT/test"

# configure apache
a2dissite 000-default
a2enmod headers
a2ensite mibew
a2enmod rewrite

# start services
service mariadb start
service apache2 start

# setup the database
mariadb --user=root --password="$MYSQL_PASS" --batch --execute \
    "CREATE DATABASE $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
     CREATE USER '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';
     GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';
     FLUSH PRIVILEGES;"

cp "$WEBROOT/configs/default_config.yml" "$WEBROOT/configs/config.yml"

# preseed configuration
CONF="$WEBROOT/configs/config.yml"

sed -i "0,/host: \".*/s//host: \"localhost\"/" $CONF
sed -i "0,/db: \".*/s//db: \"$DB_NAME\"/" $CONF
sed -i "0,/login: \".*/s//login: \"$DB_USER\"/" $CONF
sed -i "0,/pass: \".*/s//pass: \"$DB_PASS\"/" $CONF

# curl based install
URL="http://127.0.0.1/install"
CURL="curl --fail --silent --show-error -c /tmp/cookie -b /tmp/cookie"

$CURL "${URL}"
$CURL "${URL}/check-requirements"
$CURL "${URL}/check-connection"
$CURL "${URL}/create-tables"
$CURL "${URL}/set-password"
$CURL --data "password=$ADMIN_PASS&password_confirm=$ADMIN_PASS&submit=Save" "${URL}/set-password"
$CURL "${URL}/import-locales"
$CURL "${URL}/done"
$CURL "http://127.0.0.1/operator/logout"

rm -f /tmp/cookie
rm -f "$WEBROOT/install.php"

# secure sensitive files
chown www-data:www-data "$WEBROOT/configs/config.yml"
chmod 640 "$WEBROOT/configs/config.yml"

# stop services
service mariadb stop
service apache2 stop
