#!/bin/sh

# This is the init.d script for the foo cloudsql proxy service. it
# lives in /etc/init.d/foo-cloudsql-proxy, and reads the connection
# information from the metadata server. That information may well be
# hadcoded here.

### BEGIN INIT INFO
# Provides:          cloudsql
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Start-Before:    tomcat8 apache2
# Description:       Google Cloud SQL Proxy for foo
### END INIT INFO

# Name of the service
SERVICE=foo
# The location of the cloudsql-proxy binary
SCRIPT=/usr/bin/cloudsqlproxy
# The user to run the proxy as
RUNAS=root

# The connection (project, region, port is assumed to be set up in the
# GCE metadata server)
CONNECTION_ATTRIBUTE='attributes/cloud_sql_connection_name'
OPTIONS="-instances_medata=$CONNECTION_ATTRIBUTE"

PIDFILE=/var/run/cloudsql_proxy_${SERVICE}.pid
LOGFILE=/var/log/cloudsql_proxy_${SERVICE}.log

start() {
  if [ -f "/var/run/$PIDNAME" ] && kill -0 "$(cat /var/run/$PIDNAME)"; then
      echo "Service ${SERVICE} cloudsql proxyalready running" >&2
    return 1
  fi
  echo "Starting service ${SERVICE} cloudsql proxy…" >&2
  CMD="$SCRIPT $OPTIONS &> \"$LOGFILE\" & echo \$!"
  su -c "$CMD" $RUNAS > "$PIDFILE"
  echo  "Service ${SERVICE} cloudsql proxy started" >&2
}

stop() {
  if [ ! -f "$PIDFILE" ] || ! kill -0 "$(cat $PIDFILE)"; then
      echo "Service ${SERVICE} cloudsql proxy not running" >&2
    return 1
  fi
  echo "Stopping service ${SERVICE} cloudsql proxy…" >&2
  kill -15 "$(cat $PIDFILE)" && rm -f "$PIDFILE"
  echo "Service ${SERVICE} cloudsql proxy stopped" >&2
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
esac
