/build-mastodon.sh
#!/bin/sh

. lib.sh
. common.opts

load_opts "$1"

PACKAGES="$(cat pkglist-mastodon.txt | tr '[:space:]' ' ')"

set -e
set -x

JAILNAME=$MASTODON_JAILNAME
ADDR=$MASTODON_ADDR

bastille create $JAILNAME $FREEBSD_RELEASE $ADDR

IPV6_ADDR=fdcb:dbd4:3a2f:$(echo $ADDR | cut -d. -f3)::$(echo $ADDR | cut -d. -f4)
bastille config $JAILNAME set ip6.addr $IPV6_ADDR
bastille restart $JAILNAME

bastille pkg $JAILNAME install -y $PACKAGES
bastille cmd $JAILNAME pw user add mastodon -m -h - -s /bin/sh

# Install ruby
#bastille cp $JAILNAME ruby/$RUBY_SOURCE /root/
#RUBY_DIR=$(basename $RUBY_SOURCE .tar.gz)
#jexec -U root $JAILNAME /bin/sh <<SCRIPT
#set -e
#set -x
#cd
#tar xf $RUBY_DIR.tar.gz
#cd $RUBY_DIR
#./configure
#make -j8 install
#cd
#rm -rf $RUBY_DIR $RUBY_DIR.tar.gz
#gem install bundler --no-document
#SCRIPT

jexec -U mastodon $JAILNAME <<SCRIPT
set -e
set -x

cd
git clone $MASTODON_REPO live
cd ~/live
git checkout -b prod $MASTODON_VERSION
bundle config deployment 'true'
bundle config without 'development test'
# required because ruby doesn't look for native libs in /usr/local
bundle config set build.idn-ruby --with-idn-dir=/usr/local
bundle install
yarn install --pure-lockfile
SCRIPT

sed -e "s/\$DB_HOST/$POSTGRES_ADDR/" \
    -e "s/\$REDIS_HOST/$REDIS_ADDR/" \
    -e "s/\$HOSTNAME/$HOSTNAME/" \
    -e "s/\$MASTODON_ADDR/$MASTODON_ADDR/" \
    mastodon/env.production.tmpl > env.production
bastille cp $JAILNAME env.production /home/mastodon/live/.env.production
rm env.production

jexec -U mastodon $JAILNAME <<'SCRIPT'
cd ~/live
export RAILS_ENV=production
bundle exec rails assets:precompile
SCRIPT

bastille mount $JAILNAME $DATA_PATH/media usr/home/mastodon/live/public/system nullfs rw 0 0
jexec $JAILNAME /usr/sbin/chown mastodon:mastodon /home/mastodon/live/public/system
bastille mount $JAILNAME $DATA_PATH/log var/log/mastodon nullfs rw 0 0

bastille cmd $JAILNAME mkdir /usr/local/etc/newsyslog.conf.d
bastille cp $JAILNAME mastodon/newsyslog.conf /usr/local/etc/newsyslog.conf.d/mastodon.conf
bastille cp $JAILNAME mastodon/rc.d /usr/local/etc/

sed -e "s/\$HOSTNAME/$HOSTNAME/" \
    mastodon/nginx.conf.tmpl > nginx.conf
bastille cp $JAILNAME nginx.conf /usr/local/etc/nginx/
rm nginx.conf
bastille sysrc $JAILNAME nginx_enable=YES
bastille service $JAILNAME nginx start