#!/bin/sh
#
# $FreeBSD$
#

# Copyright (C) 2015 by Yuri Victorovich. All rights reserved.

# PROVIDE: gogs
# REQUIRE: LOGIN
# KEYWORD: shutdown

#
# Add the following line to /etc/rc.conf to enable gogs:
#
#gogs_enable="YES"

. /etc/rc.subr

name="gogs"
rcvar=gogs_enable
start_cmd="gogs_start"
stop_cmd="gogs_stop"

load_rc_config ${name}

: ${gogs_enable="NO"}
: ${gogs_config="/usr/local/etc/gogs/conf/app.ini"}

logfile=/var/log/gogs.log
pidfile=/var/run/gogs.pid
command="/usr/bin/true"
procname="/usr/sbin/daemon"

is_process_running() {
  [ -f $pidfile ] && procstat $(cat $pidfile) >/dev/null 2>&1
}

gogs_start() {
  if is_process_running; then
    echo "gogs is already running (pid=$(cat $pidfile))"
    return 1
  fi
  export USER=git
  export HOME=$(echo ~git)
  touch $logfile
  chmod 640 $logfile
  cd /usr/local/libexec/gogs
  /usr/sbin/daemon -P $pidfile -u git /usr/local/libexec/gogs/gogs web --config ${gogs_config} >>$logfile 2>&1
  if is_process_running; then
    echo "started gogs (pid=$(cat $pidfile))"
  else
    echo "failed to start gogs"
  fi
}

gogs_stop() {
  if is_process_running; then
    local pid=$(cat $pidfile)
    echo "stopping gogs (pid=$pid)"
    kill -- -$pid
  else
    echo "gogs isn't running"
  fi
}

run_rc_command "$1"
