#!/bin/bash
app=hubzilla

# Retrieve arguments
domain=$1
admin=$2
adminemail=$3
is_public=$4

path="/"

# Save app settings
sudo yunohost app setting $app admin -v "$admin"
sudo yunohost app setting $app is_public -v "$is_public"

# Check domain/path availability
sudo yunohost app checkurl $domain$path -a "$app"
if [[ ! $? -eq 0 ]]; then
    exit 1
fi

# Install dependencies
sudo apt-get install -y -qq php5-cli php5-imagick php5-gd php5-mcrypt

# Generate random password
db_pwd=$(dd if=/dev/urandom bs=1 count=200 2> /dev/null | tr -c -d '[A-Za-z0-9]' | sed -n 's/\(.\{24\}\).*/\1/p')

# Use 'hubzilla' as database name and user
db_user=$app

# Initialize database and store mysql password for upgrade
sudo yunohost app initdb $db_user -p $db_pwd
sudo yunohost app setting $app mysqlpwd -v $db_pwd

# Copy source files
final_path=/var/www/$app
sudo mkdir -p $final_path
sudo rsync -va ../sources/ $final_path/
sudo mkdir -p "$final_path/store/[data]/smarty3"
sudo chmod -R 777 $final_path/store

# Import database schema
sudo mysql -u $db_user -p$db_pwd $db_user < $final_path/install/schema_mysql.sql

# Copy the template install/htconfig.sample.php to .htconfig.php
sudo cp $final_path/install/htconfig.sample.php $final_path/.htconfig.php

# Use sed to add the database information to .htconfig.php
sudo sed -i "s/your.mysqlhost.com/localhost/g" $final_path/.htconfig.php
sudo sed -i "s/mysqlpassword/$db_pwd/g" $final_path/.htconfig.php
sudo sed -i "s/mysqlusername/$db_user/g" $final_path/.htconfig.php
sudo sed -i "s/mysqldatabasename/$db_user/g" $final_path/.htconfig.php
sudo sed -i "s/myredsite.example/$domain/g" $final_path/.htconfig.php
sudo sed -i "s/[\'admin_email\'] = \'\';/[\'admin_email\'] = \'$adminemail\';/g" $final_path/.htconfig.php
sudo sed -i "s/if the auto install failed, put a unique random string here/$db_pwd$db_pwd$db_pwd/g" $final_path/.htconfig.php

# Set www-data to owner
sudo chown -R www-data: $final_path

# Set up poller
sed -i "s@YNH_WWW_PATH@$final_path@g" ../conf/poller-cron
sudo cp ../conf/poller-cron /etc/cron.d/poller-cron

# Modify Nginx configuration file and copy it to Nginx conf directory
sed -i "s@YNH_WWW_PATH@$path@g" ../conf/nginx.conf
sed -i "s@YNH_WWW_ALIAS@$final_path/@g" ../conf/nginx.conf
sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf

# If app is public, add url to SSOWat conf as skipped_uris
if [ "$is_public" = "Yes" ];
then
  sudo yunohost app setting $app skipped_uris -v "/"
fi

# Restart services
sudo service nginx reload
sudo yunohost app ssowatconf
