#!/usr/bin/env bash
set -euo pipefail

############################################
# CONFIG
############################################

DOMAIN="fortnox.synktek.com"
APP_NAME="fortnox"

REPO_DIR="/var/www/${DOMAIN}"
BACKEND_DIR="${REPO_DIR}/backend"
FRONTEND_DIR="${REPO_DIR}/frontend"

DEPLOY_USER="deploy"
WEB_USER="www-data"
WEB_GROUP="www-data"

# Repo-provided configs
APACHE_HTTP_CONF="${REPO_DIR}/deploy/apache/${DOMAIN}.conf"
APACHE_HTTPS_CONF="${REPO_DIR}/deploy/apache/${DOMAIN}-le-ssl.conf"
SYSTEMD_REPO_UNIT="${REPO_DIR}/deploy/systemd/${APP_NAME}-gunicorn.service"

NVM_VERSION="v0.39.7"
NODE_MAJOR="20"

############################################
# Helpers
############################################

log() { echo -e "\n== $* =="; }

require_root() {
  [[ "$EUID" -eq 0 ]] || { echo "Run as root"; exit 1; }
}

ensure_user() {
  if ! id -u "$DEPLOY_USER" >/dev/null 2>&1; then
    adduser --disabled-password --gecos "" "$DEPLOY_USER"
  fi
}

############################################
# Start
############################################

require_root

log "Install base packages"
apt update -y
apt install -y ca-certificates curl git apache2 \
  python3 python3-venv python3-pip sudo acl

log "Create deploy user"
ensure_user

log "Ensure repo directory"
mkdir -p "$REPO_DIR"
chown -R "$DEPLOY_USER:$DEPLOY_USER" "$REPO_DIR"
chmod 755 "$REPO_DIR"

log "Allow www-data read access"
setfacl -R -m "u:${WEB_USER}:rX" "$REPO_DIR" || true
setfacl -R -d -m "u:${WEB_USER}:rX" "$REPO_DIR" || true

############################################
# .env init
############################################

log "Initialize backend .env"

if [[ ! -f "$BACKEND_DIR/.env" ]]; then
  if [[ -f "$BACKEND_DIR/.env.example" ]]; then
    cp "$BACKEND_DIR/.env.example" "$BACKEND_DIR/.env"
  else
    cat > "$BACKEND_DIR/.env" <<EOF
FLASK_ENV=production
SECRET_KEY=
SESSION_FILE_DIR=/run/${APP_NAME}/flask_session
EOF
  fi
fi

chown "$DEPLOY_USER:$WEB_GROUP" "$BACKEND_DIR/.env"
chmod 640 "$BACKEND_DIR/.env"

############################################
# Apache
############################################

log "Enable Apache modules"
a2enmod proxy proxy_http rewrite headers ssl >/dev/null

log "Install Apache configs"

[[ -f "$APACHE_HTTP_CONF" ]] || { echo "Missing $APACHE_HTTP_CONF"; exit 1; }
[[ -f "$APACHE_HTTPS_CONF" ]] || { echo "Missing $APACHE_HTTPS_CONF"; exit 1; }

cp "$APACHE_HTTP_CONF"  /etc/apache2/sites-available/
cp "$APACHE_HTTPS_CONF" /etc/apache2/sites-available/

a2ensite "${DOMAIN}.conf" >/dev/null
a2ensite "${DOMAIN}-le-ssl.conf" >/dev/null
#a2dissite 000-default.conf >/dev/null 2>&1 || true

systemctl reload apache2

############################################
# systemd (FROM REPO)
############################################

log "Install gunicorn systemd unit from repo"

[[ -f "$SYSTEMD_REPO_UNIT" ]] || {
  echo "Missing $SYSTEMD_REPO_UNIT"
  exit 1
}

cp "$SYSTEMD_REPO_UNIT" \
  "/etc/systemd/system/${APP_NAME}-gunicorn.service"

chmod 644 "/etc/systemd/system/${APP_NAME}-gunicorn.service"

systemctl daemon-reload
systemctl enable "${APP_NAME}-gunicorn.service" >/dev/null

############################################
# sudoers
############################################

log "Configure sudoers"

cat > "/etc/sudoers.d/${APP_NAME}-deploy" <<EOF
${DEPLOY_USER} ALL=(root) NOPASSWD: /bin/systemctl status ${APP_NAME}-gunicorn.service, /bin/systemctl restart ${APP_NAME}-gunicorn.service, /bin/systemctl reload apache2.service, /bin/journalctl -u ${APP_NAME}-gunicorn.service -n 200 --no-pager
EOF

chmod 440 "/etc/sudoers.d/${APP_NAME}-deploy"
visudo -c >/dev/null

############################################
# Node (nvm)
############################################

log "Install nvm + Node ${NODE_MAJOR}"

if [[ ! -d "/home/${DEPLOY_USER}/.nvm" ]]; then
  sudo -u "$DEPLOY_USER" bash -lc \
    "curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/${NVM_VERSION}/install.sh | bash"
fi

sudo -u "$DEPLOY_USER" bash -lc "
export NVM_DIR=\"\$HOME/.nvm\"
. \"\$NVM_DIR/nvm.sh\"
nvm install ${NODE_MAJOR}
nvm alias default ${NODE_MAJOR}
"

############################################
# Done
############################################

log "Provisioning complete"

cat <<EOF

Next steps:

1) As ${DEPLOY_USER}, run the repository deploy script (this creates/updates venv, installs deps,
   builds the frontend, and restarts services):

   sudo -u ${DEPLOY_USER} bash -lc 'cd ${REPO_DIR} && bash deploy/scripts/deploy.sh'

2) Verify everything is running:

   sudo systemctl status ${APP_NAME}-gunicorn --no-pager
   sudo systemctl status apache2 --no-pager

3) Smoke test locally on the server:

   curl -I http://127.0.0.1/
   curl -I http://127.0.0.1/api/  # adjust path to a real endpoint if needed

Notes:
- If deploy.sh uses sudo, make sure it calls sudo non-interactively (sudo -n), e.g.
  sudo -n systemctl restart ${APP_NAME}-gunicorn.service
  sudo -n systemctl reload apache2.service

EOF