#!/bin/bash

#=================================================
# GENERIC START
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

source _common.sh
source /usr/share/yunohost/helpers
source ynh_install_ruby
source ynh_add_secure_repos__2

#=================================================
# MANAGE SCRIPT FAILURE
#=================================================

# Exit if an error occurs during the execution of the script
ynh_abort_if_errors

#=================================================
# RETRIEVE ARGUMENTS FROM THE MANIFEST
#=================================================

domain=$YNH_APP_ARG_DOMAIN
path_url="/"
admin=$YNH_APP_ARG_ADMIN
is_public=$YNH_APP_ARG_IS_PUBLIC
language=$YNH_APP_ARG_LANGUAGE

admin_mail=$(ynh_user_get_info $admin 'mail')

app=$YNH_APP_INSTANCE_NAME

#=================================================
# CHECK IF THE APP CAN BE INSTALLED WITH THESE ARGS
#=================================================
ynh_print_info "Validating installation parameters..."

final_path=/var/www/$app
test ! -e "$final_path" || ynh_die "This path already contains a folder"

# Normalize the url path syntax
path_url=$(ynh_normalize_url_path $path_url)

# Check web path availability
ynh_webpath_available $domain $path_url
# Register (book) web path
ynh_webpath_register $app $domain $path_url

#=================================================
# STORE SETTINGS FROM MANIFEST
#=================================================
ynh_print_info "Storing installation settings..."

ynh_app_setting_set $app domain      $domain
ynh_app_setting_set $app path $path_url
ynh_app_setting_set $app admin       $admin
ynh_app_setting_set $app is_public $is_public
ynh_app_setting_set $app language    $language

#=================================================
# STANDARD MODIFICATIONS
#=================================================
# FIND AND OPEN A PORT
#=================================================
ynh_print_info "Configuring firewall..."

# Find a free port
port_web=$(ynh_find_port 3000)
port_stream=$(ynh_find_port 4000)
# Open this port
ynh_app_setting_set $app port_web    $port_web
ynh_app_setting_set $app port_stream $port_stream

#=================================================
# INSTALL DEPENDENCIES
#=================================================
ynh_print_info "Installing dependencies..."

# TODO: add in a clean way backports and yarn

# Import debian archive pubkey, need on ARM arch
arch=$(uname -m)
if [[ "$arch" = arm*  ]]; then
	apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 8B48AD6246925553
	apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7638D0442B90D010
fi

# Install extra_repo debian package backports & yarn
if [ "$(lsb_release --codename --short)" == "jessie" ]; then
	ynh_install_extra_repo --repo="deb http://httpredir.debian.org/debian jessie-backports main" --append
fi
ynh_install_extra_repo --repo="deb https://dl.yarnpkg.com/debian/ stable main" --key="https://dl.yarnpkg.com/debian/pubkey.gpg" --append

# install nodejs
ynh_install_nodejs 8

# TODO: use the same mecanism with other files
ynh_install_app_dependencies $pkg_dependencies	

#=================================================
# CREATE A POSTGRESQL DATABASE
#=================================================
ynh_print_info "Creating a PostgreSQL database..."

# Create postgresql database
db_name="${app}_production"
db_pwd=$(ynh_string_random 30)
ynh_app_setting_set "$app" db_name "$db_name"
ynh_app_setting_set "$app" db_pwd "$db_pwd"
ynh_psql_test_if_first_run
ynh_psql_create_user "$app" "$db_pwd"
ynh_psql_execute_as_root \
"CREATE DATABASE $db_name ENCODING 'UTF8' LC_COLLATE='C' LC_CTYPE='C' template=template0 OWNER $app;"

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================
ynh_print_info "Setting up source files..."

ynh_app_setting_set $app final_path $final_path
# Download, check integrity, uncompress and patch the source from app.src
mkdir $final_path
ynh_setup_source "$final_path/live"

#=================================================
# NGINX CONFIGURATION
#=================================================
ynh_print_info "Configuring nginx web server..."

# Create a dedicated nginx config
ynh_replace_string "__PORT_WEB__"    "$port_web"    "../conf/nginx.conf"
ynh_replace_string "__PORT_STREAM__" "$port_stream" "../conf/nginx.conf"
ynh_add_nginx_config

#=================================================
# CREATE DEDICATED USER
#=================================================
ynh_print_info "Configuring system user..."

# Create a system user
ynh_system_user_create $app $final_path

#=================================================
# SPECIFIC SETUP
#=================================================
# INSTALLING RUBY AND BUNDLER
#=================================================

ynh_install_ruby --ruby_version=2.6.0

/opt/rbenv/versions/2.6.0/bin/gem update --system
#/opt/rbenv/versions/2.6.0/bin/gem install bundler --no-document

#=================================================
# MODIFY A CONFIG FILE
#=================================================

cp -f ../conf/.env.production.sample "$final_path/live/.env.production"
ynh_replace_string "__DB_USER__" "$app" "$final_path/live/.env.production"
ynh_replace_string "__DB_NAME__" "$db_name" "$final_path/live/.env.production"
ynh_replace_string "__DB_PWD__" "$db_pwd" "$final_path/live/.env.production"
ynh_replace_string "__DOMAIN__" "$domain" "$final_path/live/.env.production"
ynh_replace_string "__SMTP_FROM_ADDRESS__" "$admin_mail"        "${final_path}/live/.env.production"

language="$(echo $language | head -c 2)"
ynh_replace_string "__LANGUAGE__"      "$language" "$final_path/live/.env.production"

paperclip_secret=$(head -n128 /dev/urandom | tail -n +1 | tr -dc -d 'a-z0-9' | head -c128)
ynh_replace_string "PAPERCLIP_SECRET=" "PAPERCLIP_SECRET=$paperclip_secret" "${final_path}/live/.env.production"
ynh_app_setting_set "$app" paperclip_secret "$paperclip_secret"

secret_key_base=$(head -n128 /dev/urandom | tail -n +1 | tr -dc -d 'a-z0-9' | head -c128)
ynh_replace_string "__SECRET_KEY_BASE__" "$secret_key_base" "$final_path/live/.env.production"
ynh_app_setting_set "$app" secret_key_base "$secret_key_base"

otp_secret=$(head -n128 /dev/urandom | tail -n +1 | tr -dc -d 'a-z0-9' | head -c128)
ynh_replace_string "__OTP_SECRET__" "$otp_secret" "$final_path/live/.env.production"
ynh_app_setting_set "$app" otp_secret "$otp_secret"

#=================================================
# INSTALLING MASTODON
#=================================================
ynh_print_info "Installing Mastodon..."

chown -R "$app": "$final_path"

pushd "$final_path/live"
	ynh_use_nodejs
	sudo -u "$app" env PATH=$PATH /opt/rbenv/versions/2.6.0/bin/bundle install -j$(getconf _NPROCESSORS_ONLN) --deployment --without development test
	sudo -u "$app" env PATH=$PATH yarn install --pure-lockfile
	sudo -u "$app" echo "SAFETY_ASSURED=1">> .env.production
	sudo -u "$app" env PATH=$PATH RAILS_ENV=production /opt/rbenv/versions/2.6.0/bin/bundle exec rails db:migrate --quiet
	sudo -u "$app" env PATH=$PATH RAILS_ENV=production /opt/rbenv/versions/2.6.0/bin/bundle exec rails assets:precompile --quiet
	sudo -u "$app" env PATH=$PATH RAILS_ENV=production /opt/rbenv/versions/2.6.0/bin/bundle exec rake mastodon:webpush:generate_vapid_key > key.txt
	sudo -u "$app" env PATH=$PATH RAILS_ENV=production bin/tootctl accounts create "$admin" --email="$admin_mail" --confirmed --role=admin > acc.txt
popd

admin_pass=$( tail -1 $final_path/live/acc.txt | head -1 | cut -c 15- )
ynh_secure_remove "$final_path/live/acc.txt"

vapid_private_key=$(grep -oP "VAPID_PRIVATE_KEY=\K\w+" "$final_path/live/key.txt")
vapid_public_key=$(grep -oP "VAPID_PUBLIC_KEY=\K\w+" "$final_path/live/key.txt")

ynh_replace_string "__VAPID_PRIVATE_KEY__" "$vapid_private_key"        "${final_path}/live/.env.production"
ynh_replace_string "__VAPID_PUBLIC_KEY__" "$vapid_public_key"        "${final_path}/live/.env.production"

ynh_app_setting_set "$app" vapid_private_key "$vapid_private_key"
ynh_app_setting_set "$app" vapid_public_key "$vapid_public_key"

ynh_secure_remove "$final_path/live/key.txt"

#=================================================
# SETUP CRON JOB FOR REMOVING CACHE
#=================================================
ynh_print_info "Setuping a cron job for remiving cache..."

ynh_replace_string  "__FINAL_PATH__" "$final_path" ../conf/cron
ynh_replace_string "__USER__" "$app"  ../conf/cron
sudo cp -f ../conf/cron /etc/cron.d/$app 

#=================================================
# SETUP SYSTEMD
#=================================================
ynh_print_info "Configuring a systemd service..."

# Create a dedicated systemd config
ynh_replace_string "__PORT_WEB__"    "$port_web"    "../conf/mastodon-web.service"
ynh_replace_string "__PORT_STREAM__" "$port_stream" "../conf/mastodon-streaming.service"
ynh_add_systemd_config "$app-web"       "mastodon-web.service"
ynh_add_systemd_config "$app-sidekiq"   "mastodon-sidekiq.service"
ynh_add_systemd_config "$app-streaming" "mastodon-streaming.service"

systemctl start "$app-web.service" "$app-sidekiq.service" "$app-streaming.service"

#=================================================
# STORE THE CONFIG FILE CHECKSUM
#=================================================

# Calculate and store the config file checksum into the app settings
ynh_store_file_checksum "${final_path}/live/.env.production"

#=================================================
# GENERIC FINALIZATION
#=================================================
# SECURE FILES AND DIRECTORIES
#=================================================

# Set permissions to app files
chown -R "$app": "$final_path"

#=================================================
# ADVERTISE SERVICE IN ADMIN PANEL
#=================================================

yunohost service add "$app-web"
yunohost service add "$app-sidekiq"
yunohost service add "$app-streaming"

#=================================================
# SETUP SSOWAT
#=================================================
ynh_print_info "Configuring SSOwat..."

# Make app public if necessary
if [ $is_public -eq 1 ]
then
	# unprotected_uris allows SSO credentials to be passed anyway.
	ynh_app_setting_set $app unprotected_uris "/"
fi

#=================================================
# RELOAD NGINX
#=================================================
ynh_print_info "Reloading nginx web server..."

systemctl reload nginx

#=================================================
# SEND A README FOR THE ADMIN
#=================================================

message="Mastodon was successfully installed :)
Please open 'https://$domain$path_url'
The admin email is: $admin_mail
The admin password is: $admin_pass
If you facing an issue or want to improve this app, please open a new issue in this project: https://github.com/YunoHost-Apps/mastodon_ynh"

ynh_send_readme_to_admin "$message" "$admin"

#=================================================
# END OF SCRIPT
#=================================================

ynh_print_info "Installation of $app completed"