#!/usr/bin/bash
set -Eeuo pipefail
SECRET_KEY_BASE=TOTO_EST_FLUO

## FUNCTIONS

function check_sudo_user {
    if [[ $(id -u) -eq 0 ]] || groups | grep -q sudo; then
        sudo --validate --prompt='sudo privilege required for further processing: '
    else
        >&2 echo 'current user not in the `sudo` group, aborted!'
        exit 10
    fi
}

function fetch_latest_version {
    sudo rm -rf /opt/egr
    sudo cp -r /home/pvincent/easy-going-rails /opt/egr
    sudo rm -rf /opt/egr/tmp/* 
    sudo chown -R pvincent:pvincent /opt/egr
}

function bundle_and_populate {
    cd /opt/egr
    bundle install
    DATABASE_HOST=ct1.lxd RAILS_ENV=production SECRET_KEY_BASE=$SECRET_KEY_BASE rails db:migrate
    DATABASE_HOST=ct1.lxd RAILS_ENV=production SECRET_KEY_BASE=$SECRET_KEY_BASE rails assets:precompile
}

function systemd_restart {
    DATABASE_HOST=ct1.lxd RAILS_ENV=production SECRET_KEY_BASE=$SECRET_KEY_BASE rails server --port 7000
}

## MAIN
check_sudo_user
fetch_latest_version
bundle_and_populate
systemd_restart