diff --git a/conf/nginx.conf b/conf/nginx.conf index 0a7a803..342d22f 100644 --- a/conf/nginx.conf +++ b/conf/nginx.conf @@ -1,6 +1,6 @@ -location PATHTOCHANGE { +location __PATH__ { - alias WWWPATH ; + alias __FINALPATH__; index index.html index.php ; try_files $uri $uri/ index.php; diff --git a/conf/php-fpm.conf b/conf/php-fpm.conf new file mode 100644 index 0000000..7bad39e --- /dev/null +++ b/conf/php-fpm.conf @@ -0,0 +1,392 @@ +; Start a new pool named 'www'. +; the variable $pool can we used in any directive and will be replaced by the +; pool name ('www' here) +[__NAMETOCHANGE__] + +; Per pool prefix +; It only applies on the following directives: +; - 'slowlog' +; - 'listen' (unixsocket) +; - 'chroot' +; - 'chdir' +; - 'php_values' +; - 'php_admin_values' +; When not set, the global prefix (or /usr) applies instead. +; Note: This directive can also be relative to the global prefix. +; Default Value: none +;prefix = /path/to/pools/$pool + +; Unix user/group of processes +; Note: The user is mandatory. If the group is not set, the default user's group +; will be used. +user = __USER__ +group = __USER__ + +; The address on which to accept FastCGI requests. +; Valid syntaxes are: +; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific address on +; a specific port; +; 'port' - to listen on a TCP socket to all addresses on a +; specific port; +; '/path/to/unix/socket' - to listen on a unix socket. +; Note: This value is mandatory. +listen = /var/run/php5-fpm-__NAMETOCHANGE__.sock + +; Set listen(2) backlog. +; Default Value: 128 (-1 on FreeBSD and OpenBSD) +;listen.backlog = 128 + +; Set permissions for unix socket, if one is used. In Linux, read/write +; permissions must be set in order to allow connections from a web server. Many +; BSD-derived systems allow connections regardless of permissions. +; Default Values: user and group are set as the running user +; mode is set to 0660 +listen.owner = www-data +listen.group = www-data +;listen.mode = 0660 + +; List of ipv4 addresses of FastCGI clients which are allowed to connect. +; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original +; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address +; must be separated by a comma. If this value is left blank, connections will be +; accepted from any ip address. +; Default Value: any +;listen.allowed_clients = 127.0.0.1 + +; Specify the nice(2) priority to apply to the pool processes (only if set) +; The value can vary from -19 (highest priority) to 20 (lower priority) +; Note: - It will only work if the FPM master process is launched as root +; - The pool processes will inherit the master process priority +; unless it specified otherwise +; Default Value: no set +; priority = -19 + +; Choose how the process manager will control the number of child processes. +; Possible Values: +; static - a fixed number (pm.max_children) of child processes; +; dynamic - the number of child processes are set dynamically based on the +; following directives. With this process management, there will be +; always at least 1 children. +; pm.max_children - the maximum number of children that can +; be alive at the same time. +; pm.start_servers - the number of children created on startup. +; pm.min_spare_servers - the minimum number of children in 'idle' +; state (waiting to process). If the number +; of 'idle' processes is less than this +; number then some children will be created. +; pm.max_spare_servers - the maximum number of children in 'idle' +; state (waiting to process). If the number +; of 'idle' processes is greater than this +; number then some children will be killed. +; ondemand - no children are created at startup. Children will be forked when +; new requests will connect. The following parameter are used: +; pm.max_children - the maximum number of children that +; can be alive at the same time. +; pm.process_idle_timeout - The number of seconds after which +; an idle process will be killed. +; Note: This value is mandatory. +pm = dynamic + +; The number of child processes to be created when pm is set to 'static' and the +; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'. +; This value sets the limit on the number of simultaneous requests that will be +; served. Equivalent to the ApacheMaxClients directive with mpm_prefork. +; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP +; CGI. The below defaults are based on a server without much resources. Don't +; forget to tweak pm.* to fit your needs. +; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand' +; Note: This value is mandatory. +pm.max_children = 10 + +; The number of child processes created on startup. +; Note: Used only when pm is set to 'dynamic' +; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2 +pm.start_servers = 2 + +; The desired minimum number of idle server processes. +; Note: Used only when pm is set to 'dynamic' +; Note: Mandatory when pm is set to 'dynamic' +pm.min_spare_servers = 1 + +; The desired maximum number of idle server processes. +; Note: Used only when pm is set to 'dynamic' +; Note: Mandatory when pm is set to 'dynamic' +pm.max_spare_servers = 3 + +; The number of seconds after which an idle process will be killed. +; Note: Used only when pm is set to 'ondemand' +; Default Value: 10s +;pm.process_idle_timeout = 10s; + +; The number of requests each child process should execute before respawning. +; This can be useful to work around memory leaks in 3rd party libraries. For +; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS. +; Default Value: 0 +pm.max_requests = 500 + +; The URI to view the FPM status page. If this value is not set, no URI will be +; recognized as a status page. It shows the following informations: +; pool - the name of the pool; +; process manager - static, dynamic or ondemand; +; start time - the date and time FPM has started; +; start since - number of seconds since FPM has started; +; accepted conn - the number of request accepted by the pool; +; listen queue - the number of request in the queue of pending +; connections (see backlog in listen(2)); +; max listen queue - the maximum number of requests in the queue +; of pending connections since FPM has started; +; listen queue len - the size of the socket queue of pending connections; +; idle processes - the number of idle processes; +; active processes - the number of active processes; +; total processes - the number of idle + active processes; +; max active processes - the maximum number of active processes since FPM +; has started; +; max children reached - number of times, the process limit has been reached, +; when pm tries to start more children (works only for +; pm 'dynamic' and 'ondemand'); +; Value are updated in real time. +; Example output: +; pool: www +; process manager: static +; start time: 01/Jul/2011:17:53:49 +0200 +; start since: 62636 +; accepted conn: 190460 +; listen queue: 0 +; max listen queue: 1 +; listen queue len: 42 +; idle processes: 4 +; active processes: 11 +; total processes: 15 +; max active processes: 12 +; max children reached: 0 +; +; By default the status page output is formatted as text/plain. Passing either +; 'html', 'xml' or 'json' in the query string will return the corresponding +; output syntax. Example: +; http://www.foo.bar/status +; http://www.foo.bar/status?json +; http://www.foo.bar/status?html +; http://www.foo.bar/status?xml +; +; By default the status page only outputs short status. Passing 'full' in the +; query string will also return status for each pool process. +; Example: +; http://www.foo.bar/status?full +; http://www.foo.bar/status?json&full +; http://www.foo.bar/status?html&full +; http://www.foo.bar/status?xml&full +; The Full status returns for each process: +; pid - the PID of the process; +; state - the state of the process (Idle, Running, ...); +; start time - the date and time the process has started; +; start since - the number of seconds since the process has started; +; requests - the number of requests the process has served; +; request duration - the duration in µs of the requests; +; request method - the request method (GET, POST, ...); +; request URI - the request URI with the query string; +; content length - the content length of the request (only with POST); +; user - the user (PHP_AUTH_USER) (or '-' if not set); +; script - the main script called (or '-' if not set); +; last request cpu - the %cpu the last request consumed +; it's always 0 if the process is not in Idle state +; because CPU calculation is done when the request +; processing has terminated; +; last request memory - the max amount of memory the last request consumed +; it's always 0 if the process is not in Idle state +; because memory calculation is done when the request +; processing has terminated; +; If the process is in Idle state, then informations are related to the +; last request the process has served. Otherwise informations are related to +; the current request being served. +; Example output: +; ************************ +; pid: 31330 +; state: Running +; start time: 01/Jul/2011:17:53:49 +0200 +; start since: 63087 +; requests: 12808 +; request duration: 1250261 +; request method: GET +; request URI: /test_mem.php?N=10000 +; content length: 0 +; user: - +; script: /home/fat/web/docs/php/test_mem.php +; last request cpu: 0.00 +; last request memory: 0 +; +; Note: There is a real-time FPM status monitoring sample web page available +; It's available in: ${prefix}/share/fpm/status.html +; +; Note: The value must start with a leading slash (/). The value can be +; anything, but it may not be a good idea to use the .php extension or it +; may conflict with a real PHP file. +; Default Value: not set +;pm.status_path = /status + +; The ping URI to call the monitoring page of FPM. If this value is not set, no +; URI will be recognized as a ping page. This could be used to test from outside +; that FPM is alive and responding, or to +; - create a graph of FPM availability (rrd or such); +; - remove a server from a group if it is not responding (load balancing); +; - trigger alerts for the operating team (24/7). +; Note: The value must start with a leading slash (/). The value can be +; anything, but it may not be a good idea to use the .php extension or it +; may conflict with a real PHP file. +; Default Value: not set +;ping.path = /ping + +; This directive may be used to customize the response of a ping request. The +; response is formatted as text/plain with a 200 response code. +; Default Value: pong +;ping.response = pong + +; The access log file +; Default: not set +;access.log = log/$pool.access.log + +; The access log format. +; The following syntax is allowed +; %%: the '%' character +; %C: %CPU used by the request +; it can accept the following format: +; - %{user}C for user CPU only +; - %{system}C for system CPU only +; - %{total}C for user + system CPU (default) +; %d: time taken to serve the request +; it can accept the following format: +; - %{seconds}d (default) +; - %{miliseconds}d +; - %{mili}d +; - %{microseconds}d +; - %{micro}d +; %e: an environment variable (same as $_ENV or $_SERVER) +; it must be associated with embraces to specify the name of the env +; variable. Some exemples: +; - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e +; - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e +; %f: script filename +; %l: content-length of the request (for POST request only) +; %m: request method +; %M: peak of memory allocated by PHP +; it can accept the following format: +; - %{bytes}M (default) +; - %{kilobytes}M +; - %{kilo}M +; - %{megabytes}M +; - %{mega}M +; %n: pool name +; %o: ouput header +; it must be associated with embraces to specify the name of the header: +; - %{Content-Type}o +; - %{X-Powered-By}o +; - %{Transfert-Encoding}o +; - .... +; %p: PID of the child that serviced the request +; %P: PID of the parent of the child that serviced the request +; %q: the query string +; %Q: the '?' character if query string exists +; %r: the request URI (without the query string, see %q and %Q) +; %R: remote IP address +; %s: status (response code) +; %t: server time the request was received +; it can accept a strftime(3) format: +; %d/%b/%Y:%H:%M:%S %z (default) +; %T: time the log has been written (the request has finished) +; it can accept a strftime(3) format: +; %d/%b/%Y:%H:%M:%S %z (default) +; %u: remote user +; +; Default: "%R - %u %t \"%m %r\" %s" +;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%" + +; The log file for slow requests +; Default Value: not set +; Note: slowlog is mandatory if request_slowlog_timeout is set +slowlog = /var/log/nginx/__NAMETOCHANGE__.slow.log + +; The timeout for serving a single request after which a PHP backtrace will be +; dumped to the 'slowlog' file. A value of '0s' means 'off'. +; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) +; Default Value: 0 +request_slowlog_timeout = 5s + +; The timeout for serving a single request after which the worker process will +; be killed. This option should be used when the 'max_execution_time' ini option +; does not stop script execution for some reason. A value of '0' means 'off'. +; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) +; Default Value: 0 +request_terminate_timeout = 1d + +; Set open file descriptor rlimit. +; Default Value: system defined value +;rlimit_files = 1024 + +; Set max core size rlimit. +; Possible Values: 'unlimited' or an integer greater or equal to 0 +; Default Value: system defined value +;rlimit_core = 0 + +; Chroot to this directory at the start. This value must be defined as an +; absolute path. When this value is not set, chroot is not used. +; Note: you can prefix with '$prefix' to chroot to the pool prefix or one +; of its subdirectories. If the pool prefix is not set, the global prefix +; will be used instead. +; Note: chrooting is a great security feature and should be used whenever +; possible. However, all PHP paths will be relative to the chroot +; (error_log, sessions.save_path, ...). +; Default Value: not set +;chroot = + +; Chdir to this directory at the start. +; Note: relative path can be used. +; Default Value: current directory or / when chroot +chdir = __FINALPATH__ + +; Redirect worker stdout and stderr into main error log. If not set, stdout and +; stderr will be redirected to /dev/null according to FastCGI specs. +; Note: on highloaded environement, this can cause some delay in the page +; process time (several ms). +; Default Value: no +catch_workers_output = yes + +; Limits the extensions of the main script FPM will allow to parse. This can +; prevent configuration mistakes on the web server side. You should only limit +; FPM to .php extensions to prevent malicious users to use other extensions to +; exectute php code. +; Note: set an empty value to allow all extensions. +; Default Value: .php +;security.limit_extensions = .php .php3 .php4 .php5 + +; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from +; the current environment. +; Default Value: clean env +;env[HOSTNAME] = $HOSTNAME +;env[PATH] = /usr/local/bin:/usr/bin:/bin +;env[TMP] = /tmp +;env[TMPDIR] = /tmp +;env[TEMP] = /tmp + +; Additional php.ini defines, specific to this pool of workers. These settings +; overwrite the values previously defined in the php.ini. The directives are the +; same as the PHP SAPI: +; php_value/php_flag - you can set classic ini defines which can +; be overwritten from PHP call 'ini_set'. +; php_admin_value/php_admin_flag - these directives won't be overwritten by +; PHP call 'ini_set' +; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no. + +; Defining 'extension' will load the corresponding shared extension from +; extension_dir. Defining 'disable_functions' or 'disable_classes' will not +; overwrite previously defined php.ini values, but will append the new value +; instead. + +; Note: path INI options can be relative and will be expanded with the prefix +; (pool, global or /usr) + +; Default Value: nothing is defined by default except the values in php.ini and +; specified at startup with the -d argument +;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com +;php_flag[display_errors] = off +;php_admin_value[error_log] = /var/log/fpm-php.www.log +;php_admin_flag[log_errors] = on +;php_admin_value[memory_limit] = 32M \ No newline at end of file diff --git a/conf/php-fpm.ini b/conf/php-fpm.ini new file mode 100644 index 0000000..18ddf9c --- /dev/null +++ b/conf/php-fpm.ini @@ -0,0 +1 @@ +post_max_size=30M \ No newline at end of file diff --git a/manifest.json b/manifest.json index 4e069de..dc2dc7c 100644 --- a/manifest.json +++ b/manifest.json @@ -5,35 +5,51 @@ "en": "A minimalist web chat", "fr": "Un web chat minimaliste" }, + "packaging_format": 1, + "requirements": { + "yunohost": ">> 2.3.15" + }, "license": "MIT", "developer": { "name": "chtixof" }, - "multi_instance": "false", + "multi_instance": true, + "services": [ + "nginx", + "php5-fpm" + ], + "license": "MIT", "arguments": { - "install" : [ { + "install" : [ + { "name": "domain", + "type": "domain", "ask": { "en": "Choose a domain for minchat", - "en": "Choisissez un domaine pour minchat" + "fr": "Choisissez un domaine pour minchat" }, "example": "domain.org" - },{ + }, + { "name": "path", + "type": "path", "ask": { "en": "Choose a path for minchat", - "en": "Choisissez un chemin pour minchat" + "fr": "Choisissez un chemin pour minchat" }, "example": "/minchat", "default": "/minchat" - },{ - "name": "ispublic", + }, + { + "name": "is_public", + "type": "boolean", "ask": { - "en": "Is it a public site (Y)", - "en": "Taper Y si le site est public" + "en": "Is it a public minchat site ?", + "fr": "Est-ce un site public ?" }, - "example": "Y", - "default": "Y" - } ] + "choices": ["true", "false"], + "default": "true" + } + ] } } \ No newline at end of file diff --git a/scripts/_common b/scripts/_common new file mode 100644 index 0000000..9584cf1 --- /dev/null +++ b/scripts/_common @@ -0,0 +1,265 @@ +MINCHAT_VERSION="1.1" +MINCHAT_SOURCE_URL="https://github.com/wojtek77/chat/archive/master.tar.gz" +MINCHAT_SOURCE_SHA256="1a290c8ae2d48a84457366291e1d733cddf587751c6953e12da03f511b4b7df5" + +QUIET () { # Redirige la sortie standard dans /dev/null + $@ > /dev/null +} + +ALL_QUIET () { # Redirige la sortie standard et d'erreur dans /dev/null + $@ > /dev/null 2>&1 +} + +# Substitute a string by another in a file +# +# usage: ynh_substitute_char string_to_find replace_string file_to_analyse +# | arg: string_to_find - String to replace in the file +# | arg: replace_string - New string that will replace +# | arg: file_to_analyse - File where the string will be replaced. +ynh_substitute_char () { + delimit=@ + match_char=${1//${delimit}/"\\${delimit}"} # Escape the delimiter if it's in the string. + replace_char=${2//${delimit}/"\\${delimit}"} + workfile=$3 + + sudo sed --in-place "s${delimit}${match_char}${delimit}${replace_char}${delimit}g" "$workfile" +} + +ynh_store_checksum_config () { + config_file_checksum=checksum_${1//[\/ ]/_} # Replace all '/' and ' ' by '_' + ynh_app_setting_set $app $config_file_checksum $(sudo md5sum "$1" | cut -d' ' -f1) +} + +extract_source() { + local DESTDIR=$1 + + # retrieve and extract Minichat tarball + rc_tarball="${DESTDIR}/privatebin.tar.gz" + sudo wget -q -O "$rc_tarball" "$MINCHAT_SOURCE_URL" \ + || ynh_die "Unable to download source tarball" + echo "$MINCHAT_SOURCE_SHA256 $rc_tarball" | sha256sum -c >/dev/null \ + || ynh_die "Invalid checksum of downloaded tarball" + sudo tar xf "$rc_tarball" -C "$DESTDIR" --strip-components 1 \ + || ynh_die "Unable to extract source tarball" + sudo rm "$rc_tarball" +} + +ynh_nginx_config () { + finalnginxconf="/etc/nginx/conf.d/$domain.d/$app.conf" + ynh_compare_checksum_config "$finalnginxconf" 1 + sudo cp ../conf/nginx.conf "$finalnginxconf" + + # To avoid a break by set -u, use a void substitution ${var:-}. If the variable is not set, it's simply set with an empty variable. + # Substitute in a nginx config file only if the variable is not empty + if test -n "${path:-}"; then + ynh_substitute_char "__PATH__" "$path" "$finalnginxconf" + fi + if test -n "${domain:-}"; then + ynh_substitute_char "__DOMAIN__" "$domain" "$finalnginxconf" + fi + if test -n "${port:-}"; then + ynh_substitute_char "__PORT__" "$port" "$finalnginxconf" + fi + if test -n "${app:-}"; then + ynh_substitute_char "__NAME__" "$app" "$finalnginxconf" + fi + if test -n "${final_path:-}"; then + ynh_substitute_char "__FINALPATH__" "$final_path" "$finalnginxconf" + fi + ynh_store_checksum_config "$finalnginxconf" + + sudo systemctl reload nginx +} + +ynh_store_checksum_config () { + config_file_checksum=checksum_${1//[\/ ]/_} # Replace all '/' and ' ' by '_' + ynh_app_setting_set $app $config_file_checksum $(sudo md5sum "$1" | cut -d' ' -f1) +} + +ynh_remove_nginx_config () { + ynh_secure_remove "/etc/nginx/conf.d/$domain.d/$app.conf" + sudo systemctl reload nginx +} + +ynh_fpm_config () { + finalphpconf="/etc/php5/fpm/pool.d/$app.conf" + ynh_compare_checksum_config "$finalphpconf" 1 + sudo cp ../conf/php-fpm.conf "$finalphpconf" + ynh_substitute_char "__NAMETOCHANGE__" "$app" "$finalphpconf" + ynh_substitute_char "__FINALPATH__" "$final_path" "$finalphpconf" + ynh_substitute_char "__USER__" "$app" "$finalphpconf" + sudo chown root: "$finalphpconf" + ynh_store_checksum_config "$finalphpconf" + + if [ -e "../conf/php-fpm.ini" ] + then + finalphpini="/etc/php5/fpm/conf.d/20-$app.ini" + ynh_compare_checksum_config "$finalphpini" 1 + sudo cp ../conf/php-fpm.ini "$finalphpini" + sudo chown root: "$finalphpini" + ynh_store_checksum_config "$finalphpini" + fi + + sudo systemctl reload php5-fpm +} + +ynh_remove_fpm_config () { + ynh_secure_remove "/etc/php5/fpm/pool.d/$app.conf" + ynh_secure_remove "/etc/php5/fpm/conf.d/20-$app.ini" + sudo systemctl reload php5-fpm +} + +# Remove a file or a directory securely +# +# usage: ynh_secure_remove path_to_remove +# | arg: path_to_remove - File or directory to remove +ynh_secure_remove () { + path_to_remove=$1 + forbidden_path=" \ + /var/www \ + /home/yunohost.app" + + if [[ "$forbidden_path" =~ "$path_to_remove" \ + # Match all path or subpath in $forbidden_path + || "$path_to_remove" =~ ^/[[:alnum:]]+$ \ + # Match all first level path from / (Like /var, /root, etc...) + || "${path_to_remove:${#path_to_remove}-1}" = "/" ]] + # Match if the path finish by /. Because it's seems there is an empty variable + then + echo "Avoid deleting of $path_to_remove." >&2 + else + if [ -e "$path_to_remove" ] + then + sudo rm -R "$path_to_remove" + else + echo "$path_to_remove doesn't deleted because it's not exist." >&2 + fi + fi +} + +# Create a system user +# +# usage: ynh_system_user_create user_name [home_dir] +# | arg: user_name - Name of the system user that will be create +# | arg: home_dir - Path of the home dir for the user. Usually the final path of the app. If this argument is omitted, the user will be created without home +ynh_system_user_create () { + if ! ynh_system_user_exists "$1" # Check if the user exists on the system + then # If the user doesn't exist + if [ $# -ge 2 ]; then # If a home dir is mentioned + user_home_dir="-d $2" + else + user_home_dir="--no-create-home" + fi + sudo useradd $user_home_dir --system --user-group $1 --shell /usr/sbin/nologin || ynh_die "Unable to create $1 system account" + fi +} + +# Delete a system user +# +# usage: ynh_system_user_delete user_name +# | arg: user_name - Name of the system user that will be create +ynh_system_user_delete () { + if ynh_system_user_exists "$1" # Check if the user exists on the system + then + echo "Remove the user $1" >&2 + sudo userdel $1 + else + echo "The user $1 was not found" >&2 + fi +} + +ynh_compare_checksum_config () { + current_config_file=$1 + compress_backup=${2:-0} # If $2 is empty, compress_backup will set at 0 + config_file_checksum=checksum_${current_config_file//[\/ ]/_} # Replace all '/' and ' ' by '_' + checksum_value=$(ynh_app_setting_get $app $config_file_checksum) + if [ -n "$checksum_value" ] + then # Proceed only if a value was stocked into the app config + if ! echo "$checksum_value $current_config_file" | md5sum -c --status + then # If the checksum is now different + backup_config_file="$current_config_file.backup.$(date '+%d.%m.%y_%Hh%M,%Ss')" + if [ compress_backup -eq 1 ] + then + sudo tar --create --gzip --file "$backup_config_file.tar.gz" "$current_config_file" # Backup the current config file and compress + backup_config_file="$backup_config_file.tar.gz" + else + sudo cp -a "$current_config_file" "$backup_config_file" # Backup the current config file + fi + echo "Config file $current_config_file has been manually modified since the installation or last upgrade. So it has been duplicated in $backup_config_file" >&2 + echo "$backup_config_file" # Return the name of the backup file + fi + fi +} + +ynh_backup_fail_upgrade () { + WARNING echo "Upgrade failed." + app_bck=${app//_/-} # Replace all '_' by '-' + if sudo yunohost backup list | grep -q $app_bck-pre-upgrade$backup_number; then # Vérifie l'existence de l'archive avant de supprimer l'application et de restaurer + sudo yunohost app remove $app # Supprime l'application avant de la restaurer. + sudo yunohost backup restore --ignore-hooks $app_bck-pre-upgrade$backup_number --apps $app --force # Restore the backup if upgrade failed + ynh_die "The app was restored to the way it was before the failed upgrade." + fi +} + +ynh_backup_before_upgrade () { # Backup the current version of the app, restore it if the upgrade fails + backup_number=1 + old_backup_number=2 + app_bck=${app//_/-} # Replace all '_' by '-' + if sudo yunohost backup list | grep -q $app_bck-pre-upgrade1; then # Vérifie l'existence d'une archive déjà numéroté à 1. + backup_number=2 # Et passe le numéro de l'archive à 2 + old_backup_number=1 + fi + + sudo yunohost backup create --ignore-hooks --apps $app --name $app_bck-pre-upgrade$backup_number # Créer un backup différent de celui existant. + if [ "$?" -eq 0 ]; then # Si le backup est un succès, supprime l'archive précédente. + if sudo yunohost backup list | grep -q $app_bck-pre-upgrade$old_backup_number; then # Vérifie l'existence de l'ancienne archive avant de la supprimer, pour éviter une erreur. + QUIET sudo yunohost backup delete $app_bck-pre-upgrade$old_backup_number + fi + else # Si le backup a échoué + ynh_die "Backup failed, the upgrade process was aborted." + fi +} + +# Manage a fail of the script +# +# Print a warning to inform that the script was failed +# Execute the ynh_clean_setup function if used in the app script +# +# usage of ynh_clean_setup function +# This function provide a way to clean some residual of installation that not managed by remove script. +# To use it, simply add in your script: +# ynh_clean_setup () { +# instructions... +# } +# This function is optionnal. +# +# Usage: ynh_exit_properly is used only by the helper ynh_check_error. +# You must not use it directly. +ynh_exit_properly () { + exit_code=$? + if [ "$exit_code" -eq 0 ]; then + ynh_die # Exit without error if the script ended correctly + fi + + trap '' EXIT # Ignore new exit signals + set +eu # Do not exit anymore if a command fail or if a variable is empty + + echo -e "!!\n $app's script has encountered an error. Its execution was cancelled.\n!!" >&2 + + if type -t ynh_clean_setup > /dev/null; then # Check if the function exist in the app script. + ynh_clean_setup # Call the function to do specific cleaning for the app. + fi + + ynh_die # Exit with error status +} + +# Exit if an error occurs during the execution of the script. +# +# Stop immediatly the execution if an error occured or if a empty variable is used. +# The execution of the script is derivate to ynh_exit_properly function before exit. +# +# Usage: ynh_abort_if_errors +ynh_abort_if_errors () { + set -eu # Exit if a command fail, and if a variable is used unset. + trap ynh_exit_properly EXIT # Capturing exit signals on shell script +} \ No newline at end of file diff --git a/scripts/backup b/scripts/backup index 5ab9fec..0ebfb5d 100644 --- a/scripts/backup +++ b/scripts/backup @@ -1,15 +1,26 @@ #!/bin/bash -app=minchat -# The parameter $1 is the backup directory location +# causes the shell to exit if any subcommand or pipeline returns a non-zero status +set -eu + +# Source YNH helpers +source /usr/share/yunohost/helpers + +app=$YNH_APP_INSTANCE_NAME + +# Retrieve arguments +domain=$(ynh_app_setting_get "$app" domain) + +# Backup directory location for the app from where the script is executed and # which will be compressed afterward -backup_dir=$1/apps/$app -mkdir -p $backup_dir +backup_dir=$YNH_APP_BACKUP_DIR # Backup sources & data -sudo cp -a /var/www/$app/. $backup_dir/sources +ynh_backup "/var/www/${app}" "sources" -# Copy Nginx and YunoHost parameters to make the script "standalone" -sudo cp -a /etc/yunohost/apps/$app/. $backup_dir/yunohost -domain=$(sudo yunohost app setting $app domain) -sudo cp -a /etc/nginx/conf.d/$domain.d/$app.conf $backup_dir/nginx.conf \ No newline at end of file +# Copy Nginx conf +sudo mkdir -p ./conf +ynh_backup "/etc/nginx/conf.d/${domain}.d/${app}.conf" "conf/nginx.conf" +# Copy the php-fpm conf files +ynh_backup "/etc/php5/fpm/pool.d/${app}.conf" "php-fpm.conf" +ynh_backup "/etc/php5/fpm/conf.d/20-${app}.ini" "php-fpm.ini" \ No newline at end of file diff --git a/scripts/install b/scripts/install index 3e73da5..f6ca648 100644 --- a/scripts/install +++ b/scripts/install @@ -1,38 +1,51 @@ #!/bin/bash -# Installation de minchat dans Yunohost -app=minchat + +# Exit on command errors and treat unset variables as an error +set -eu + +# Source app helpers +source ./_common +source /usr/share/yunohost/helpers # Retrieve arguments -domain=$1 -path=$2 -is_public=$3 +domain=$YNH_APP_ARG_DOMAIN +path=$YNH_APP_ARG_PATH +is_public=$YNH_APP_ARG_IS_PUBLIC + +app=$YNH_APP_INSTANCE_NAME # Check domain/path availability -sudo yunohost app checkurl $domain$path -a $app -if [[ ! $? -eq 0 ]]; then - exit 1 +sudo yunohost app checkurl "${domain}${path}" -a "$app" \ + || ynh_die "Path not available: ${domain}${path}" + +# Remove trailing "/" for next commands +if [[ ! "$path" == "/" ]]; then + path=${path%/} fi +# Copy files to the right place +final_path=/var/www/$app +sudo mkdir -p $final_path +extract_source $final_path + +# Create system user dedicace for this app +ynh_system_user_create $app + # Copy files to the right place with the right permissions final_path=/var/www/$app sudo mkdir -p $final_path -sudo cp -a ../sources/* $final_path -if [[ ! -f ${final_path}/conf/setup.ini ]] ; then - sudo cp ${final_path}/conf/sample/setup.ini ${final_path}/conf/ -fi -sudo chown -R www-data: $final_path +sudo chown -R $app: $final_path # Modify Nginx configuration file and copy it to Nginx conf directory -sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf -sed -i "s@WWWPATH@$final_path@g" ../conf/nginx.conf -sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf +ynh_nginx_config -# Make it public is required -if [[ $is_public =~ ^[Yy]$ ]] -then - sudo yunohost app setting $app skipped_uris -v "/" +# Create the php-fpm pool config +ynh_fpm_config + +# Set ssowat config +if [[ $is_public -eq 0 ]]; then + ynh_app_setting_delete $app skipped_uris fi -# Reload nginx and regenerate SSOwat conf -sudo service nginx reload +sudo systemctl reload nginx sudo yunohost app ssowatconf \ No newline at end of file diff --git a/scripts/remove b/scripts/remove index 8337669..e4fcab5 100644 --- a/scripts/remove +++ b/scripts/remove @@ -1,15 +1,22 @@ #!/bin/bash -app=minchat + +# Exit on command errors and treat unset variables as an error +set -u + +# Source app helpers +source ./_common +source /usr/share/yunohost/helpers + +# Get multi-instances specific variables +app=$YNH_APP_INSTANCE_NAME # Retrieve arguments -domain=$(sudo yunohost app setting $app domain) +domain=$(ynh_app_setting_get "$app" domain) -# Remove sources -sudo rm -rf /var/www/$app +ynh_secure_remove /var/www/$app +ynh_secure_remove /etc/nginx/conf.d/$domain.d/$app.conf +ynh_remove_fpm_config -# Remove configuration files -sudo rm -f /etc/nginx/conf.d/$domain.d/$app.conf +ynh_system_user_delete $app -# Restart services -sudo service nginx reload -sudo yunohost app ssowatconf +sudo systemctl reload nginx \ No newline at end of file diff --git a/scripts/restore b/scripts/restore index a9d083b..69e60e4 100644 --- a/scripts/restore +++ b/scripts/restore @@ -1,16 +1,66 @@ #!/bin/bash -app=minchat -# The parameter $1 is the uncompressed restore directory location -backup_dir=$1/apps/$app +# causes the shell to exit if any subcommand or pipeline returns a non-zero status +set -eu + +# Source app helpers +source /usr/share/yunohost/helpers + +app=$YNH_APP_INSTANCE_NAME + +# Retrieve arguments +domain=$(ynh_app_setting_get "$app" domain) +path=$(ynh_app_setting_get "$app" path) +user=$(ynh_app_setting_get $app allowed_users) +is_public=$(ynh_app_setting_get $app is_public) + +# Check domain/path availability +sudo yunohost app checkurl "${domain}${path}" -a "$app" \ + || ynh_die "Path not available: ${domain}${path}" + +# Check $final_path +final_path="/var/www/${app}" +if [ -d $final_path ]; then + ynh_die "There is already a directory: $final_path" +fi + +# Check configuration files +nginx_conf="/etc/nginx/conf.d/${domain}.d/${app}.conf" +if [ -f $nginx_conf ]; then + ynh_die "The NGINX configuration already exists at '${nginx_conf}'. + You should safely delete it before restoring this app." +fi +# Check configuration files php-fpm +phpfpm_conf="/etc/php5/fpm/pool.d/php-fpm-${app}.conf" +if [ -f $phpfpm_conf ]; then + ynh_die "The PHP FPM configuration already exists at '${phpfpm_conf}'. + You should safely delete it before restoring this app." +fi + +phpfpm_ini="/etc/php5/fpm/conf.d/20-${app}.ini" +if [ -f $phpfpm_ini ]; then + ynh_die "The PHP FPM INI configuration already exists at '${phpfpm_ini}'. + You should safely delete it before restoring this app." +fi # Restore sources & data -sudo cp -a $backup_dir/sources/. /var/www/$app +sudo cp -a "./sources" $final_path -# Restore Nginx and YunoHost parameters -sudo cp -a $backup_dir/yunohost/. /etc/yunohost/apps/$app -domain=$(sudo yunohost app setting $app domain) -sudo cp -a $backup_dir/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf +# Set permissions +sudo chown -R $app: $final_path -# Restart webserver -sudo service nginx reload \ No newline at end of file +# Restore configuration files +sudo cp -a ./conf/nginx.conf "${nginx_conf}" + +# Restore php-fpm configuration files +sudo cp -a ./conf/php-fpm.conf "${phpfpm_conf}" +sudo cp -a ./conf/php-fpm.ini "${phpfpm_ini}" + +# Set ssowat config +if [[ $is_public -eq 0 ]]; then + ynh_app_setting_delete $app skipped_uris +fi + +# Reload service +sudo systemctl reload nginx +sudo yunohost app ssowatconf \ No newline at end of file diff --git a/scripts/upgrade b/scripts/upgrade index 4e3de49..c63dc9d 100644 --- a/scripts/upgrade +++ b/scripts/upgrade @@ -1,26 +1,58 @@ #!/bin/bash -app=minchat -# Retrieve arguments -domain=$(sudo yunohost app setting $app domain) -path=$(sudo yunohost app setting $app path) +# Exit on command errors and treat unset variables as an error +set -eu +# Source app helpers +source ./_common +source /usr/share/yunohost/helpers + +app=$YNH_APP_INSTANCE_NAME + +domain=$(ynh_app_setting_get "$app" domain) +path=$(ynh_app_setting_get "$app" path) +user=$(ynh_app_setting_get "$app" user) +is_public=$(ynh_app_setting_get $app is_public) + +ynh_backup_before_upgrade # Backup the current version of the app +ynh_clean_setup () { + ynh_backup_fail_upgrade # restore it if the upgrade fails +} +ynh_abort_if_errors # Active trap pour arrêter le script si une erreur est détectée. # Remove trailing "/" for next commands -path=${path%/} - -# Copy source files -final_path=/var/www/$app -sudo mkdir -p $final_path -sudo cp -a ../sources/* $final_path -if [[ ! -f ${final_path}/conf/setup.ini ]] ; then - sudo cp ${final_path}/conf/sample/setup.ini ${final_path}/conf/ +if [[ ! "$path" == "/" ]]; then + path=${path%/} fi + +# Create system user dedicace for this app +ynh_system_user_create $app + +# Init final_path, if ever it got deleted somehow +final_path=/var/www/$app + +# Clean all files and directory except the data directory +ynh_secure_remove $final_path + +# Create directory +sudo mkdir -p $final_path + +# Copy files to the right place +extract_source $final_path + +# Fix owner +sudo chown -R $app: $final_path + # Modify Nginx configuration file and copy it to Nginx conf directory -sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf -sed -i "s@WWWPATH@$final_path@g" ../conf/nginx.conf -sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf +ynh_nginx_config -# Restart services -sudo service nginx reload +# Create the php-fpm pool config +ynh_fpm_config + +# Set ssowat config +if [[ $is_public -eq 1 ]]; then + ynh_app_setting_set "$app" unprotected_uris "/" +fi + +# Reload Nginx +sudo systemctl reload nginx sudo yunohost app ssowatconf -