diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b72f9be --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*~ +*.swp diff --git a/README.md b/README.md index 65d06bd..891f0c8 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,21 @@ # lstu_ynh -DON'T WORK/ NE FONCTIONNE PAS !! +Seems to work, but need some testing. + +## Todo + +- [ ] Integrate with LDAP +- [ ] Add a question for the admin features' password +- [ ] Allow to choose the database (sqlite or PostgreSQL) +- [ ] Allow to choose to use Minion +- [ ] Add CI stuff + +# Contributing To contribute see the package lutim_ynh as example. Pour contribuer regardez le paquet lutim_ynh comme exemple. lutim_ynh : https://github.com/YunoHost-Apps/lutim_ynh -Site officiel de lstu: https://git.framasoft.org/luc/lstu +Site officiel de lstu: https://framagit.org/luc/lstu diff --git a/conf/logrotate b/conf/logrotate new file mode 100644 index 0000000..d116834 --- /dev/null +++ b/conf/logrotate @@ -0,0 +1,21 @@ + +__FINALPATH__/log/production.log { + # Effectue une rotation des logs tout les mois + monthly + # Ou si le fichier de log dépasse 100Mo + size 100M + # Garde un maximum de 12 anciens logs + rotate 12 + # Compresse pas les logs avec gzip + compress + # Compresse le log au cycle suivant. Donc garde toujours 2 logs non compressés. + delaycompress + # Copie et tronque le journal pour permettre la poursuite de l'écriture. Plutôt que de déplacer le log. + copytruncate + # Ne renvoi pas d'erreur si le fichier de log est absent. + missingok + # Ne fait pas de rotation si le log est vide. + notifempty + # Garde les anciens logs dans le même dossier. + noolddir +} diff --git a/conf/lstu-minion@.service b/conf/lstu-minion@.service new file mode 100644 index 0000000..cc9931a --- /dev/null +++ b/conf/lstu-minion@.service @@ -0,0 +1,12 @@ +[Unit] +Description=Shortened URLs service job queue +Documentation=https://framagit.org/luc/lstu + +[Service] +Type=simple +User=www-data +WorkingDirectory=__FINALPATH__ +ExecStart=/usr/local/bin/carton exec script/application minion worker + +[Install] +WantedBy=multi-user.target diff --git a/conf/lstu.conf.template b/conf/lstu.conf.template index 78b6c45..3206286 100644 --- a/conf/lstu.conf.template +++ b/conf/lstu.conf.template @@ -66,12 +66,28 @@ # optional #fixed_domain => 'example.org', + # choose what database you want to use + # valid choices are sqlite and postgresql (all lowercase) + # optional, default is sqlite + #dbtype => 'sqlite', + + # SQLite ONLY - only used if dbtype is set to sqlite # define a path to the SQLite database # you can define it relative to lstu directory or set an absolute path # remember that it has to be in a directory writable by Lstu user # optional, default is lstu.db #db_path => 'lstu.db', + # PostgreSQL ONLY - only used if dbtype is set to postgresql + # these are the credentials to access the PostgreSQL database + # mandatory if you choosed postgresql as dbtype + #pgdb => { + # database => 'lstu', + # host => 'localhost', + # #user => 'DBUSER', + # #pwd => 'DBPASSWORD' + #}, + # Rate-limiting for the API # After ban_min_strike requests in a second, the IP address will be # banned for one hour. @@ -80,6 +96,14 @@ # optional, default is 3 ban_min_strike => 3, + # Ban whitelist + # You can whitelist IP addresses to prevent you from being banned + # Be careful, the IP addresses are compared as string, not as IP addresses + # a network range will not work + # Example of valid input: ban_whitelist => ['198.51.100.42', '2001:0DB8::42'],¬ + # optional, default is an empty array + #ban_whitelist => [], + # define an URL to the Piwik instance and the ID of a website to track # set if you want to track views in Piwik # optional, Piwik tracking is disabled by default diff --git a/conf/lstu.service b/conf/lstu.service index 8fb354c..12f3aac 100644 --- a/conf/lstu.service +++ b/conf/lstu.service @@ -1,6 +1,6 @@ [Unit] -Description=URL Shortener -Documentation=https://git.framasoft.org/luc/lstu +Description=Shortened URLs service +Documentation=https://framagit.org/luc/lstu Requires=network.target After=network.target @@ -10,9 +10,9 @@ User=www-data RemainAfterExit=yes WorkingDirectory=__FINALPATH__ PIDFile=__FINALPATH__script/hypnotoad.pid -ExecStart=/usr/bin/carton exec hypnotoad script/lstu -ExecStop=/usr/bin/carton exec hypnotoad -s script/lstu -ExecReload=/usr/bin/carton exec hypnotoad script/lstu +ExecStart=/usr/local/bin/carton exec hypnotoad script/lstu +ExecStop=/usr/local/bin/carton exec hypnotoad -s script/lstu +ExecReload=/usr/local/bin/carton exec hypnotoad script/lstu [Install] WantedBy=multi-user.target diff --git a/conf/nginx.conf b/conf/nginx.conf index 22f455b..3e674d7 100644 --- a/conf/nginx.conf +++ b/conf/nginx.conf @@ -1,35 +1,21 @@ location __PATH__ { - if ($scheme = http) { - rewrite ^ https://$server_name$request_uri? permanent; - } - location ~ [^/]\.php(/|$) { - fastcgi_split_path_info ^(.+?\.php)(/.*)$; - fastcgi_pass unix:/var/run/php5-fpm.sock; - fastcgi_index index.php; - include fastcgi_params; - fastcgi_param REMOTE_USER $remote_user; - fastcgi_param PATH_INFO $fastcgi_path_info; + if ($scheme = http) { + rewrite ^ https://$server_name$request_uri? permanent; } - # Include SSOWAT user panel. - include conf.d/yunohost_panel.conf.inc; + #--PRIVATE--# Include SSOWAT user panel. + #--PRIVATE--include conf.d/yunohost_panel.conf.inc; - # This is important for user's privacy ! - access_log off; + access_log /var/log/nginx/lstu.access.log; error_log /var/log/nginx/lstu.error.log; - # This is important ! Make it OK with your Lutim configuration - client_max_body_size 40M; - proxy_pass http://127.0.0.1:__PORT__; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - - # Lutim reads this header and understands that the current session is actually HTTPS. - # Enable it if you run a HTTPS server (in this case, don't forgot to change the listen port $ - proxy_set_header X-Forwarded-Proto https; + proxy_set_header X-Remote-Port $remote_port; + proxy_set_header X-Forwarded-Proto $scheme; # We expect the downsteam servers to redirect to the right hostname, so don't do any rewrite$ proxy_redirect off; diff --git a/manifest.json b/manifest.json index 9de22bd..b2d6861 100644 --- a/manifest.json +++ b/manifest.json @@ -40,23 +40,14 @@ "example": "/lstu", "default": "/lstu" }, - { - "name": "admin", - "type": "user", - "ask": { - "en": "Choose the Lutim administrator (must be an existing YunoHost user)", - "fr": "Choisissez un administrateur Lutim (doit être un utilisateur YunoHost)" - }, - "example": "john" - }, { "name": "is_public", + "type": "boolean", "ask": { - "en": "Uploading images is it public?", - "fr": "L'upload des images est-il public ?" + "en": "Is it a public application?", + "fr": "Est-ce une application publique ?" }, - "choices": ["Yes", "No"], - "default": "No" + "default": false } ] } diff --git a/scripts/.fonctions b/scripts/.fonctions index 2c69f20..d3b7eac 100644 --- a/scripts/.fonctions +++ b/scripts/.fonctions @@ -1,55 +1,64 @@ #!/bin/bash +# vim:set noexpandtab: -CHECK_VAR () { # Vérifie que la variable n'est pas vide. -# $1 = Variable à vérifier -# $2 = Texte à afficher en cas d'erreur +ynh_version="2.5" + +YNH_VERSION () { # Returns the version number of the Yunohost moulinette + ynh_version=$(sudo yunohost -v | grep "moulinette:" | cut -d' ' -f2 | cut -d'.' -f1,2) +} + +CHECK_VAR () { # Verifies that the variable is not empty. + # $1 = Variable to be checked + # $2 = Display text on error test -n "$1" || (echo "$2" >&2 && false) } -EXIT_PROPERLY () { # Provoque l'arrêt du script en cas d'erreur. Et nettoye les résidus. - exit_code=$? - if [ "$exit_code" -eq 0 ]; then - exit 0 # Quitte sans erreur si le script se termine correctement. - fi - trap '' EXIT - set +eu +EXIT_PROPERLY () { # Causes the script to stop in the event of an error. And clean the residue. + trap '' ERR echo -e "\e[91m \e[1m" # Shell in light red bold echo -e "!!\n $app install's script has encountered an error. Installation was cancelled.\n!!" >&2 - if type -t CLEAN_SETUP > /dev/null; then # Vérifie l'existance de la fonction avant de l'exécuter. - CLEAN_SETUP # Appel la fonction de nettoyage spécifique du script install. + if type -t CLEAN_SETUP > /dev/null; then # Checks the existence of the function before executing it. + CLEAN_SETUP # Call the specific cleanup function of the install script. fi - # Compense le bug de ssowat qui ne supprime pas l'entrée de l'app en cas d'erreur d'installation. + # Compensates the ssowat bug that does not remove the app's input in case of installation error. sudo sed -i "\@\"$domain$path/\":@d" /etc/ssowat/conf.json + if [ "$ynh_version" = "2.2" ]; then + /bin/bash $script_dir/remove + fi + ynh_die } TRAP_ON () { # Activate signal capture - set -eu # Exit if a command fail, and if a variable is used unset. - trap EXIT_PROPERLY EXIT # Capturing exit signals on shell script + trap EXIT_PROPERLY ERR # Capturing exit signals on error } -CHECK_USER () { # Vérifie la validité de l'user admin -# $1 = Variable de l'user admin. +TRAP_OFF () { # Ignoring signal capture until TRAP_ON + trap '' ERR # Ignoring exit signals +} + +CHECK_USER () { # Check the validity of the user admin + # $1 = User admin variable ynh_user_exists "$1" || (echo "Wrong admin" >&2 && false) } -CHECK_PATH () { # Vérifie la présence du / en début de path. Et son absence à la fin. - if [ "${path:0:1}" != "/" ]; then # Si le premier caractère n'est pas un / - path="/$path" # Ajoute un / en début de path +CHECK_PATH () { # Checks / at the beginning of the path. And his absence at the end. + if [ "${path:0:1}" != "/" ]; then # If the first character is not / + path="/$path" # Add / at the beginning of path fi - if [ "${path:${#path}-1}" == "/" ] && [ ${#path} -gt 1 ]; then # Si le dernier caractère est un / et que ce n'est pas le seul caractère. - path="${path:0:${#path}-1}" # Supprime le dernier caractère + if [ "${path:${#path}-1}" == "/" ] && [ ${#path} -gt 1 ]; then # If the last character is a / and it is not the only character. + path="${path:0:${#path}-1}" # Delete last character fi } -CHECK_DOMAINPATH () { # Vérifie la disponibilité du path et du domaine. +CHECK_DOMAINPATH () { # Checks the availability of the path and domain. sudo yunohost app checkurl $domain$path -a $app } -CHECK_FINALPATH () { # Vérifie que le dossier de destination n'est pas déjà utilisé. +CHECK_FINALPATH () { # Checks that the destination folder is not already in use. final_path=/var/www/$app if [ -e "$final_path" ] then @@ -58,67 +67,71 @@ CHECK_FINALPATH () { # Vérifie que le dossier de destination n'est pas déjà u fi } -GENERATE_DB () { # Créer une base de données et un utilisateur dédié au nom de l'app. -# $1 = Nom de la base de donnée - db_user=$1 - db_user=${db_user//-/_} # mariadb ne supporte pas les - dans les noms de base de données. Ils sont donc remplacé par des _ - # Génère un mot de passe aléatoire. -# db_pwd=$(head -n20 /dev/urandom | tr -c -d 'A-Za-z0-9' | head -c20) - db_pwd=$(ynh_string_random) - CHECK_VAR "$db_pwd" "db_pwd empty" - # Utilise '$app' comme nom d'utilisateur et de base de donnée - # Initialise la base de donnée et stocke le mot de passe mysql. - ynh_mysql_create_db "$db_user" "$db_user" $db_pwd - ynh_app_setting_set $app mysqlpwd $db_pwd +SETUP_SOURCE () { # Download source, decompress and copu into $final_path + src=$(cat ../sources/source_md5 | awk -F' ' {'print $2'}) + sudo wget -nv -i ../sources/source_url -O $src + # Checks the checksum of the downloaded source. + # md5sum -c ../sources/source_md5 --status || ynh_die "Corrupt source" + # Decompress source + if [ "$(echo ${src##*.})" == "tgz" ]; then + tar -x -f $src + elif [ "$(echo ${src##*.})" == "zip" ]; then + unzip -q $src + else + false # Unsupported archive format. + fi + # Copy file source + sudo cp -a $(cat ../sources/source_dir)/. "$final_path" + # Copy additional file and modified + if test -e "../sources/ajouts"; then + sudo cp -a ../sources/ajouts/. "$final_path" + fi } -ADD_SYS_USER () { # Créer un utilisateur système dédié à l'app - if ! ynh_system_user_exists "$app" # Test l'existence de l'utilisateur - then - sudo useradd -d /var/www/$app --system --user-group $app --shell /usr/sbin/nologin || (echo "Unable to create $app system account" >&2 && false) - fi +ADD_SYS_USER () { # Créer un utilisateur système dédié à l'app + if ! ynh_system_user_exists "$app" # Test l'existence de l'utilisateur + then + sudo useradd -d /var/www/$app --system --user-group $app --shell /usr/sbin/nologin || (echo "Unable to create $app system account" >&2 && false) + fi } -POOL_FPM () { # Créer le fichier de configuration du pool php-fpm et le configure. - sed -i "s@__NAMETOCHANGE__@$app@g" ../conf/php-fpm.conf - sed -i "s@__FINALPATH__@$final_path@g" ../conf/php-fpm.conf - sed -i "s@__USER__@$app@g" ../conf/php-fpm.conf - finalphpconf=/etc/php5/fpm/pool.d/$app.conf - sudo cp ../conf/php-fpm.conf $finalphpconf - sudo chown root: $finalphpconf - finalphpini=/etc/php5/fpm/conf.d/20-$app.ini - sudo cp ../conf/php-fpm.ini $finalphpini - sudo chown root: $finalphpini - sudo service php5-fpm reload -} - -STORE_MD5_CONFIG () { # Enregistre la somme de contrôle du fichier de config -# $1 = Nom du fichier de conf pour le stockage dans settings.yml -# $2 = Nom complet et chemin du fichier de conf. +STORE_MD5_CONFIG () { # Saves the checksum of the config file + # $1 = Name of the conf file for storage in settings.yml + # $2 = Full name and path of the conf file. ynh_app_setting_set $app $1_file_md5 $(sudo md5sum "$2" | cut -d' ' -f1) } -CHECK_MD5_CONFIG () { # Créé un backup du fichier de config si il a été modifié. -# $1 = Nom du fichier de conf pour le stockage dans settings.yml -# $2 = Nom complet et chemin du fichier de conf. +CHECK_MD5_CONFIG () { # Created a backup of the config file if it was changed. + # $1 = Name of the conf file for storage in settings.yml + # $2 = Full name and path of the conf file.onf. if [ "$(ynh_app_setting_get $app $1_file_md5)" != $(sudo md5sum "$2" | cut -d' ' -f1) ]; then sudo cp -a "$2" "$2.backup.$(date '+%d.%m.%y_%Hh%M,%Ss')" # Si le fichier de config a été modifié, créer un backup. fi } -FIND_PORT () { # Cherche un port libre. -# $1 = Numéro de port pour débuter la recherche. - port=$1 - while ! sudo yunohost app checkport $port ; do - port=$((port+1)) - done - CHECK_VAR "$port" "port empty" +FIND_PORT () { # Search free port + YNH_VERSION + if [ $ynh_version == "2.5" ]; then + # $1 = Port number to start the search. + port=$1 + while ! sudo yunohost app checkport $port ; do + port=$((port+1)) + done + CHECK_VAR "$port" "port empty" + else + # $1 = Port number to start the search. + port=$1 + if [ "$(sudo yunohost tools port-available $port)" = "True" ]; then + port=$((port+1)) + fi + CHECK_VAR "$port" "port empty" + fi } ### REMOVE SCRIPT -REMOVE_NGINX_CONF () { # Suppression de la configuration nginx +REMOVE_NGINX_CONF () { # Delete nginx configuration if [ -e "/etc/nginx/conf.d/$domain.d/$app.conf" ]; then # Delete nginx config echo "Delete nginx config" sudo rm "/etc/nginx/conf.d/$domain.d/$app.conf" @@ -126,39 +139,27 @@ REMOVE_NGINX_CONF () { # Suppression de la configuration nginx fi } -REMOVE_FPM_CONF () { # Suppression de la configuration du pool php-fpm - if [ -e "/etc/php5/fpm/pool.d/$app.conf" ]; then # Delete fpm config - echo "Delete fpm config" - sudo rm "/etc/php5/fpm/pool.d/$app.conf" - fi - if [ -e "/etc/php5/fpm/conf.d/20-$app.ini" ]; then # Delete php config - echo "Delete php config" - sudo rm "/etc/php5/fpm/conf.d/20-$app.ini" - fi - sudo service php5-fpm reload -} - -REMOVE_LOGROTATE_CONF () { # Suppression de la configuration de logrotate +REMOVE_LOGROTATE_CONF () { # Delete logrotate configuration if [ -e "/etc/logrotate.d/$app" ]; then echo "Delete logrotate config" sudo rm "/etc/logrotate.d/$app" fi } -SECURE_REMOVE () { # Suppression de dossier avec vérification des variables - chaine="$1" # L'argument doit être donné entre quotes simple '', pour éviter d'interpréter les variables. +SECURE_REMOVE () { # Deleting a folder with variable verification + chaine="$1" # The argument must be given between simple quotes '', to avoid interpreting the variables. no_var=0 - while (echo "$chaine" | grep -q '\$') # Boucle tant qu'il y a des $ dans la chaine + while (echo "$chaine" | grep -q '\$') # Loop as long as there are $ in the string do no_var=1 - global_var=$(echo "$chaine" | cut -d '$' -f 2) # Isole la première variable trouvée. - only_var=\$$(expr "$global_var" : '\([A-Za-z0-9_]*\)') # Isole complètement la variable en ajoutant le $ au début et en gardant uniquement le nom de la variable. Se débarrasse surtout du / et d'un éventuel chemin derrière. - real_var=$(eval "echo ${only_var}") # `eval "echo ${var}` permet d'interpréter une variable contenue dans une variable. + global_var=$(echo "$chaine" | cut -d '$' -f 2) # Isole the first variable found. + only_var=\$$(expr "$global_var" : '\([A-Za-z0-9_]*\)') # Isole completely the variable by adding the $ at the beginning and keeping only the name of the variable. Mostly gets rid of / and a possible path behind. + real_var=$(eval "echo ${only_var}") # `eval "echo ${var}` Allows to interpret a variable contained in a variable. if test -z "$real_var" || [ "$real_var" = "/" ]; then echo "Variable $only_var is empty, suppression of $chaine cancelled." >&2 return 1 fi - chaine=$(echo "$chaine" | sed "s@$only_var@$real_var@") # remplace la variable par sa valeur dans la chaine. + chaine=$(echo "$chaine" | sed "s@$only_var@$real_var@") # Replaces variable with its value in the string. done if [ "$no_var" -eq 1 ] then @@ -173,20 +174,57 @@ SECURE_REMOVE () { # Suppression de dossier avec vérification des variable fi } -REMOVE_BDD () { # Suppression de la base de donnée et de l'utilisateur associé. -# $1 = Nom de la base de donnée - # Utilise '$app' comme nom d'utilisateur et de base de donnée - db_user=$1 - if mysqlshow -u root -p$(sudo cat $MYSQL_ROOT_PWD_FILE) | grep -q "^| $db_user"; then - echo "Delete db" - ynh_mysql_drop_db $db_user - ynh_mysql_drop_user $db_user +REMOVE_SYS_USER () { # Delete user + if ynh_system_user_exists "$app" # Test user exist + then + sudo userdel $app fi } -REMOVE_SYS_USER () { # Supprime l'utilisateur système dédié à l'app - if ynh_system_user_exists "$app" # Test l'existence de l'utilisateur - then - sudo userdel $app - fi +#================================================= +# BACKUP +#================================================= + +# 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 } diff --git a/scripts/backup b/scripts/backup new file mode 100644 index 0000000..deaac93 --- /dev/null +++ b/scripts/backup @@ -0,0 +1,27 @@ +#!/bin/bash +# vim:set noexpandtab: + +# Exit on command errors and treat unset variables as an error +set -eu + +# Source app helpers +source /usr/share/yunohost/helpers + +# Get multi-instances specific variables +app=$YNH_APP_INSTANCE_NAME + +# Retrieve app settings +domain=$(ynh_app_setting_get "$app" domain) + +# Copy the app files +final_path="/var/www/${app}" +ynh_backup "${final_path}" "sources" 1 + +# Copy the nginx conf files +ynh_backup "/etc/nginx/conf.d/${domain}.d/${app}.conf" "nginx.conf" + +# Copy the lstu conf file +ynh_backup "${final_path}/lstu.conf" "lstu.conf" +ynh_backup "/etc/systemd/system/lstu.service" "systemd_lstu.service" +ynh_backup "/etc/logrotate.d/${app}" "logrotate_lstu" +ynh_backup "/var/log/${app}/production.log" "production.log" diff --git a/scripts/install b/scripts/install index f19edbb..1ac6557 100644 --- a/scripts/install +++ b/scripts/install @@ -1,85 +1,91 @@ #!/bin/bash +# vim:set noexpandtab: -source .fonctions # Charge les fonctions génériques habituellement utilisées dans le script +# Exit on command errors and treat unset variables as an error +set -eu + +source .fonctions # Loads the generic functions usually used in the script +source /usr/share/yunohost/helpers # Source app helpers CLEAN_SETUP () { -# Nettoyage des résidus d'installation non pris en charge par le script remove. -# Pas de nettoyage supplémentaire nécessaire ici... + # Clean installation residues that are not supported by the remove script. + # Clean hosts echo "" } -TRAP_ON # Active trap pour arrêter le script si une erreur est détectée. +TRAP_ON # Active trap to stop the script if an error is detected. # Retrieve arguments domain=$YNH_APP_ARG_DOMAIN path=$YNH_APP_ARG_PATH -admin=$YNH_APP_ARG_ADMIN is_public=$YNH_APP_ARG_IS_PUBLIC app=$YNH_APP_INSTANCE_NAME -# Source app helpers -source /usr/share/yunohost/helpers - script_dir=$PWD -# Vérifie que les variables ne sont pas vides. +# Check variables are not empty CHECK_VAR "$app" "app name not set" CHECK_VAR "$script_dir" "script_dir not set" +CHECK_PATH # Check and fix path syntax +CHECK_DOMAINPATH # Check and fix domain disponibility -CHECK_USER "$admin" # Vérifie la validité de l'user admin +CHECK_FINALPATH # Check final path -CHECK_PATH # Vérifie et corrige la syntaxe du path. -CHECK_DOMAINPATH # Vérifie la disponibilité du path et du domaine. - -CHECK_FINALPATH # Vérifie que le dossier de destination n'est pas déjà utilisé. - -# Modifie le domaine pour qu'il passe dans une regex +# Check domain with regex domain_regex=$(echo "$domain" | sed 's@-@.@g') CHECK_VAR "$domain_regex" "domain_regex empty" -FIND_PORT 8080 # Cherche un port libre. +FIND_PORT 8096 # Check port availability -# Enregistre les infos dans la config YunoHost -ynh_app_setting_set $app admin $admin +# Save app settings ynh_app_setting_set $app domain $domain ynh_app_setting_set $app is_public $is_public ynh_app_setting_set $app port $port +# Install dependencies +ynh_package_update +ynh_package_install build-essential libssl-dev libpq-dev -# Créer le repertoire de destination et stocke son emplacement. +# Copy files to the right place +sudo mkdir "${final_path}" ynh_app_setting_set $app final_path $final_path -sudo git clone https://framagit.org/luc/lstu.git $final_path # Télécharge la source, décompresse et copie dans $final_path +# Get source +SETUP_SOURCE -# Copie le fichier de config nginx +# Copy it to Nginx conf directory sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf +if [ $is_public -eq 1 ]; +then + sudo sed -i "s@#--PRIVATE--@@g" /etc/nginx/conf.d/$domain.d/$app.conf +fi -# Installation de perlmagick, interface perl pour imagemagick et de carton, gestionnaire de dépendances perl -sudo apt-get update -sudo apt-get install carton perlmagick -qy +## Copy and fix variable into lstu config +sudo cp ../conf/lstu.conf.template "${final_path}/lstu.conf" +sudo sed -i "s@__DOMAIN__@$domain@g" "${final_path}/lstu.conf" +sudo sed -i "s@__PATH__@$path@g" "${final_path}/lstu.conf" +sudo sed -i "s@__PORT__@$port@g" "${final_path}/lstu.conf" -## Copie et configuration du fichier de conf. -sudo cp ../conf/lstu.conf.template "$final_path/lstu.conf" -sudo sed -i "s@__DOMAIN__@$domain@g" "$final_path/lstu.conf" -sudo sed -i "s@__PATH__@$path@g" "$final_path/lstu.conf" -sudo sed -i "s@__PORT__@$port@g" "$final_path/lstu.conf" +secret=$(ynh_string_random 24) +CHECK_VAR "$secret" "secret empty" +sudo sed -i "s@__SECRET__@$secret@g" "${final_path}/lstu.conf" +STORE_MD5_CONFIG "lstu.conf" "${final_path}/lstu.conf" +# Install systemd script +sudo cp ../conf/lstu.service /etc/systemd/system/lstu.service +sudo chown root: /etc/systemd/system/lstu.service +sudo sed -i "s@__FINALPATH__@$final_path/@g" /etc/systemd/system/lstu.service -codename=$(lsb_release -a 2>/dev/null | grep Codename | cut -f 2) -CHECK_VAR "$codename" "codename empty" -ynh_app_setting_set $app codename $codename -sudo cp "$final_path/utilities/lstu.default" /etc/default/lstu +# Install logrotate +sudo cp ../conf/logrotate /etc/logrotate.d/$app +sed -i "s@__FINALPATH__@$final_path@g" /etc/logrotate.d/$app - sudo cp ../conf/lstu.service /etc/systemd/system/lstu.service - sudo chown root: /etc/systemd/system/lstu.service - sudo sed -i "s@__FINALPATH__@$final_path/@g" /etc/systemd/system/lstu.service - ## Démarrage auto du service - sudo systemctl enable lstu.service +# Install Carton +echo yes | sudo cpan Carton - -# Installation de lstu via carton +# Install lstu's dependencies via carton sudo mkdir -p /var/log/$app/ cd $final_path sudo carton install 2>&1 | sudo tee -a "/var/log/$app/setup_carton.log" @@ -90,12 +96,12 @@ sudo sed -i "s@__PORT__@$port@g" /etc/nginx/conf.d/$domain.d/$app.conf # Make app public or private ynh_app_setting_set $app skipped_uris "/" -if [ "$is_public" = "No" ]; -then # Si l'app est privée, seul le visionnage des images reste public +if [ $is_public -eq 0 ]; +then # If the app is private, only the shortened URLs are publics if [ "$path" == "/" ]; then - path="" # Si path correspond à la racine, supprime le / pour éviter une erreur de la regex. + path="" fi - ynh_app_setting_set $app protected_regex "$domain_regex$path/stats$","$domain_regex$path/manifest.webapp$","$domain_regex$path/$","$domain_regex$path/d/.*$","$domain_regex$path/m/.*$" + ynh_app_setting_set $app protected_regex "$domain_regex$path/login$","$domain_regex$path/logout$","$domain_regex$path/api$","$domain_regex$path/extensions$","$domain_regex$path/stats$","$domain_regex$path/d/.*$","$domain_regex$path/a$","$domain_regex$path/$" fi # Making log symbolic link to /var/log @@ -103,20 +109,27 @@ sudo touch /var/log/$app/production.log sudo chown www-data: /var/log/$app/production.log sudo ln -s /var/log/$app/production.log "$final_path/log/production.log" -# Configure les droits d'accès au fichiers +# Configure owner sudo chown -R www-data: $final_path -# Start lutim -sudo service lstu start +# Start lstu +sudo systemctl daemon-reload +sudo systemctl start lstu.service +sudo systemctl enable lstu.service + # Set right permissions on new files created at first start sudo chown -R www-data: "$final_path" - -# Add lutim as a service +# Add lstu as a service sudo yunohost service add lstu -l $final_path/log/production.log +if [ $is_public -eq 0 ]; +then + # Delete public access + ynh_app_setting_delete $app unprotected_uris + # Regenerate SSOwat's configuration + sudo yunohost app ssowatconf +fi -# Recharge la configuration Nginx +# Reload Nginx sudo service nginx reload -# Régénère la configuration de SSOwat -sudo yunohost app ssowatconf diff --git a/scripts/remove b/scripts/remove index 5b7737c..0217a54 100644 --- a/scripts/remove +++ b/scripts/remove @@ -1,45 +1,47 @@ #!/bin/bash +# vim:set noexpandtab: -source .fonctions # Charge les fonctions génériques habituellement utilisées dans le script +# Exit on command errors and treat unset variables as an error +set -u -# Récupère les infos de l'application. +source .fonctions # Loads the generic functions usually used in the script +source /usr/share/yunohost/helpers # Source app helpers + +# Get multi-instances specific variables app=$YNH_APP_INSTANCE_NAME -# Source app helpers -source /usr/share/yunohost/helpers - domain=$(ynh_app_setting_get $app domain) -# Arrêt du service -if [ -e "/etc/init.d/lutim" ]; then - echo "Delete init.d script" - sudo service lstu stop - sudo rm "/etc/init.d/lstu" - sudo rm "/etc/default/lstu" - sudo update-rc.d -f lstu remove -fi +# Stop lstu service if [ -e "/etc/systemd/system/lstu.service" ]; then echo "Delete systemd script" - sudo service lstu stop - sudo rm "/etc/systemd/system/lstu.service" + sudo systemctl stop lstu.service sudo systemctl disable lstu.service + sudo rm "/etc/systemd/system/lstu.service" + systemctl daemon-reload fi -# Retire le service du monitoring de Yunohost. -if sudo yunohost service status | grep -q lutim # Test l'existence du service dans Yunohost +# Remove monitoring service Yunohost. +if sudo yunohost service status | grep -q lstu # Test the existence of the service in Yunohost then echo "Remove lstu service" sudo yunohost service remove lstu fi -SECURE_REMOVE '/var/www/$app' # Suppression du dossier de l'application +SECURE_REMOVE '/var/www/$app' # Delete directory application -REMOVE_NGINX_CONF # Suppression de la configuration nginx +REMOVE_NGINX_CONF # Delete nginx configuration -SECURE_REMOVE '/var/log/$app/' # Suppression des log +SECURE_REMOVE '/var/log/$app/' # Delete log -# Régénère la configuration de SSOwat +REMOVE_LOGROTATE_CONF # Delete logrotate configuration + +ynh_package_remove build-essential || echo "build-essential already uninstalled" +ynh_package_remove libssl-dev || echo "libssl-dev already uninstalled" +ynh_package_remove libpq-dev || echo "libpq-dev already uninstalled" + +# Reload SSOwat configuration sudo yunohost app ssowatconf echo -e "\e[0m" # Restore normal color diff --git a/scripts/restore b/scripts/restore new file mode 100644 index 0000000..fc7d554 --- /dev/null +++ b/scripts/restore @@ -0,0 +1,97 @@ +#!/bin/bash +# vim:set noexpandtab: +# This restore script is adapted to Yunohost >=2.4 + +# Exit on command errors and treat unset variables as an error +set -eu + +# Source app helpers +source /usr/share/yunohost/helpers + +# The parameter $app is the id of the app instance ex: ynhexample__2 +app=$YNH_APP_INSTANCE_NAME + +# Get old parameter of the app +domain=$(ynh_app_setting_get $app domain) +path=$(ynh_app_setting_get $app path) +is_public=$(ynh_app_setting_get $app is_public) + +ynh_package_update +ynh_package_install build-essential libssl-dev libpq-dev +echo yes | sudo cpan Carton + +# 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 +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 lstu +lstu_conf="${final_path}/${app}.conf" +if [ -f "${lstu_conf}" ]; then + ynh_die "The LSTU CONF configuration already exists at '${lstu_conf}'. You should safely delete it before restoring this app." +fi + +lstu_systemd="/etc/systemd/system/${app}.service" +if [ -f "${lstu_systemd}" ]; then + ynh_die "The LSTU SYSTEMD configuration already exists at '${lstu_systemd}'. You should safely delete it before restoring this app." +fi + +lstu_logrotate="/etc/logrotate.d/${app}" +if [ -f "${lstu_logrotate}" ]; then + ynh_die "The LSTU LOGROTATE configuration already exists at '${lstu_logrotate}'. You should safely delete it before restoring this app." +fi + +lstu_log="/var/log/${app}/production.log" +if [ -f "${lstu_log}" ]; then + ynh_die "The LSTU LOG configuration already exists at '${lstu_log}'. You should safely delete it before restoring this app." +fi + + # Restore sources & data +sudo cp -a ./sources "${final_path}" + +# Set permissions +sudo chown -R www-data: "${final_path}" + +# Restore nginx configuration files +sudo cp -a ./nginx.conf "${nginx_conf}" + +# Restore lstu configuration files +sudo cp -a ./lstu.conf "${lstu_conf}" + +# Restore service +sudo cp -a ./systemd_lstu.service "${lstu_systemd}" + +sudo cp -a ./logrotate_lstu "${lstu_logrotate}" + +# Create log production +sudo mkdir "/var/log/${app}/" +sudo cp -a ./production.log "${lstu_log}" +# Delete symbolic link and restore +sudo rm -fr "${final_path}/log/production.log" +sudo ln -s "/var/log/${app}/production.log" "${final_path}/log/production.log" + +# Reload lstu service +sudo systemctl daemon-reload +sudo systemctl start lstu.service +sudo systemctl enable lstu.service + +# Set ssowat config +if [ $is_public -eq 0 ]; +then + ynh_app_setting_delete $app skipped_uris +fi + +# Reload services +sudo systemctl reload nginx +sudo yunohost app ssowatconf diff --git a/scripts/upgrade b/scripts/upgrade new file mode 100644 index 0000000..45a279b --- /dev/null +++ b/scripts/upgrade @@ -0,0 +1,132 @@ +#!/bin/bash +# vim:set noexpandtab: + +set -eu + +#================================================= +# GENERIC STARTING +#================================================= +# IMPORT GENERIC HELPERS +#================================================= + +source .fonctions +source /usr/share/yunohost/helpers + +#================================================= +# LOAD SETTINGS +#================================================= + +app=$YNH_APP_INSTANCE_NAME + +domain=$(ynh_app_setting_get $app domain) +path=$(ynh_app_setting_get $app path) +is_public=$(ynh_app_setting_get $app is_public) +port=$(ynh_app_setting_get $app port) +final_path=$(ynh_app_setting_get $app final_path) +secret=$(ynh_app_setting_get $app secret) + +#================================================= +# FIX OLD THINGS +#================================================= + +if [ "$is_public" = "Yes" ]; then + ynh_app_setting_set $app is_public 1 # Fixe is_public en booléen + is_public=1 +elif [ "$is_public" = "No" ]; then + ynh_app_setting_set $app is_public 0 + is_public=0 +fi + +if [ "${#final_path}" -eq 0 ] +then # Si final_path n'est pas renseigné dans la config yunohost, cas d'ancien script, code final_path en dur + final_path=/var/www/$app +fi + +CHECK_PATH # Checks and corrects the syntax of the path. + +# Get source +SETUP_SOURCE + +#================================================= +# NGINX CONFIGURATION +#================================================= + +# Copy Nginx configuration file +sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf +# Modify Nginx configuration file +sudo sed -i "s@__PATH__@$path@g" /etc/nginx/conf.d/$domain.d/$app.conf +sudo sed -i "s@__PORT__@$port@g" /etc/nginx/conf.d/$domain.d/$app.conf + +if [ $is_public -eq 1 ]; +then + sudo sed -i "s@#--PRIVATE--@@g" /etc/nginx/conf.d/$domain.d/$app.conf +fi + +#================================================= +# SPECIFIC UPGRADE +#================================================= +# SETUP LSTU +#================================================= + +## Copie et configuration du fichier de conf. +CHECK_MD5_CONFIG "lstu.conf" "$final_path/lstu.conf" # Créé un backup du fichier de config si il a été modifié. +sudo cp ../conf/lstu.conf.template "$final_path/lstu.conf" +sudo sed -i "s@__DOMAIN__@$domain@g" "$final_path/lstu.conf" +sudo sed -i "s@__PATH__@$path@g" "$final_path/lstu.conf" +sudo sed -i "s@__PORT__@$port@g" "$final_path/lstu.conf" +sudo sed -i "s@__SECRET__@$secret@g" "${final_path}/lstu.conf" +STORE_MD5_CONFIG "lstu.conf" "$final_path/lstu.conf" # Réenregistre la somme de contrôle du fichier de config + +#================================================= +# SETUP SYSTEMD +#================================================= + +# Mise en place du script systemd +sudo systemctl stop $app +sudo cp ../conf/lstu.service /etc/systemd/system/$app.service +sudo chown root: /etc/systemd/system/$app.service +sudo sed -i "s@__FINALPATH__@$final_path/@g" /etc/systemd/system/$app.service +## +sudo systemctl daemon-reload +## Démarrage auto du service +sudo systemctl enable $app + +#================================================= +# UPDATE LSTU'S DEPENDENCIES WITH CARTON +#================================================= + +pushd $final_path # cd avec une stack pour revenir en arrière +echo yes | sudo carton install 2>&1 | sudo tee -a "/var/log/$app/setup_carton.log" +popd # Revient au dossier courant avant pushd + +#================================================= +# SECURING FILES AND DIRECTORIES +#================================================= + +sudo chown -R www-data: $final_path + +#================================================= +# RESTART LSTU +#================================================= + +sudo systemctl start lstu.service + +#================================================= +# SETUP SSOWAT +#================================================= + +ynh_app_setting_set $app skipped_uris "/" +if [ $is_public -eq 0 ]; +then # If the app is private, only the shortened URLs are publics + if [ "$path" == "/" ]; then + path="" + fi + ynh_app_setting_set $app protected_regex "$domain_regex$path/login$","$domain_regex$path/logout$","$domain_regex$path/api$","$domain_regex$path/extensions$","$domain_regex$path/stats$","$domain_regex$path/d/.*$","$domain_regex$path/a$","$domain_regex$path/$" +fi + +#================================================= +# RELOAD NGINX +#================================================= + +sudo systemctl reload nginx +sudo yunohost app ssowatconf