#!/bin/bash

######################################################################
#
#  Copyright (c) 2015 arakasi72 (https://github.com/arakasi72)
#
#  --> Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
######################################################################

parent_pid() {
    # Look up the parent of the given PID.
    pid=${1:-$$}
    stat=($(</proc/${pid}/stat))
    echo ${stat[3]}
}

user=$1
PARENT=$(parent_pid $PPID)
passfile='/etc/nginx/.htpasswd'

echo "Set rutorrent web interface password for $user"

if ! [ "$(ps --no-heading -o %c $PARENT)" = "rtpass" ]; then
  echo "Can only be run using rtpass"
  exit 1
elif [ -z "$(grep $user $passfile)" ]; then
  echo "Invalid user. Please contact your sysadmin for assistance"
  exit 1
else
  htpasswd $passfile $user
fi
