From baf7392c22a5d28d8bc0659279bcce9eb23e9f04 Mon Sep 17 00:00:00 2001
From: Kubat <mael.martin31@gmail.com>
Date: Wed, 2 Dec 2020 19:28:39 +0100
Subject: [PATCH] WIP: Install with sshfs

---
 README.md     |  60 +++++++++---------
 generate.sh   |   9 ---
 matrixpack.sh | 165 --------------------------------------------------
 stpkg         |  76 ++++++++++++++++++-----
 4 files changed, 93 insertions(+), 217 deletions(-)
 delete mode 100755 generate.sh
 delete mode 100755 matrixpack.sh

diff --git a/README.md b/README.md
index 3bd9947..255ead4 100644
--- a/README.md
+++ b/README.md
@@ -58,7 +58,7 @@ Pour cela:
 3. Se déplacer dans le dépôt et exécuter le script `stpkg`
   ```bash
   cd matrix-stickers
-  ./stpkg --install
+  ./stpkg -install
   ```
 4. Se connecter à Element. Utiliser la commande `/devtools` dans n'importe quel tchat.
    ![devtools](screenshots/screen_devtools.png)
@@ -111,7 +111,7 @@ Un pack de stickers se résume à un fichier json possédant des informations pr
 Pour créer ce ficher json et téléverser ses images, il existe deux méthodes :
 
 ### Méthode automatique (Recommandé)
-**Via le script matrixpack.sh**
+**Via stpkg**
 **Requis** : *ImageMagick* (en tant que root : `apt install imagemagick`/`pacman -S imagemagick`).
 Ce script suppose que vous avez déjà créer un ou plusieurs dossiers regroupant les images que vous souhaitez utiliser en sticker.
 Le nom du dossier définira le nom du pack, et les images s'y trouvant deviendront les stickers du pack.
@@ -121,32 +121,27 @@ Le nom du dossier définira le nom du pack, et les images s'y trouvant deviendro
   ```
 2. Se connecter à Element et récupérer l'**access token** de son compte en allant dans
    `Tout les paramètres` -> `Aide & À propos` -> `Avancé`. Dans la dernière ligne `Jeton d'accès` cliquer pour l'afficher.
-3. Exécuter le script matrixpack.sh
+3. Utilisez la commande `stpkg pack`, vous devriez avoir `stpkg` dans votre path à ce moment
   ```bash
-  cd matrix-stickers
+  # on détéctant le nom du pack
   read ACCESS_TOKEN # coller l'acces token puis faire "entrer"
-  ./matrixpack.sh $ACCESS_TOKEN homeserver directory1 directory2...
+  stpkg pack -t $ACCESS_TOKEN directory
+  # ou en spécifiant le nom du pack
+  read ACCESS_TOKEN
+  stpkg pack -t $ACCESS_TOKEN name directory
+  # ou sans stocker l'access token dans une variable de votre shell
+  stpkg pack name directory # l'access token vous sera demandé, coller puis faire "entrer"
   ```
-- Note : Le (ou les) dossier cible `directory` correpond au dossier contenant vos images à téléverser.
-Le script crée un nouveau sous-dossier dans `directory` contenant trois fichiers:
+4. Vous pouvez activer le pack créé avec la commande `stpkg add <nom du pack>`.
+- Note : Le dossier `directory` correpond au dossier contenant vos images à téléverser.
+Le script `stpkg` va créer un dossier dans les packs du repo contenant trois fichiers :
     - nomdupack.json : le json des stickers téléversés, rognés, de taille 128x128, sans palette indexée (qui casse la transparence)
     - preview.png : une prévisualisation des images en mosaïque avec **ImageMagick**
     - README.md: Permet d'afficher les stickers du pack dans git
-4. Ajouter le json des stickers téléversés (nomdupack.json) dans le dossier `packs`.
-  ```bash
-  cp nomdupack.json ~/html/stickerpicker/web/packs
-  ```
-**Précision** : si vous avez exécuté le script hors de votre perso, vous devez envoyer le ficher json par ssh.
-  ```bash
-  scp nomdupack.json nomArise@perso.iiens.net:~/html/stickerpicker/web/packs
-  ```
-Cela va copier le fichier nomdupack.json dans le dossier `packs` se trouvant dans votre perso.
-5. Mettre à jour le fichier `index.json` se trouvant dans `~/html/stickerpicker/web/packs`.
 
-**Facultatif :**
-Vous pouvez aussi ajouter le nouveau sous-dossier créé par le script dans ce dépôt et ainsi contribuer !
-Pour cela faites une pull request. Pensez à demander l'accès à un fork déjà existant plustôt que de créer
-le votre pour économiser de la place, les disques c'est pas gratuit.
+**Facultatif :** allez dans le dossier du repo des stickers, faites un commits et une merge request pour contribuer.
+   Pensez à demander l'accès à un fork déjà existant plustôt que de créer
+   le votre pour économiser de la place, les disques c'est pas gratuit.
 
 **Tips**
 ```bash
@@ -196,20 +191,31 @@ scp matrix-stickers/packs/*/*.json nom0000@perso.iiens.net:html/stickerpicker/we
 5. Ajouter le json à index.json
 
 ## Utilisation de stpkg
-
 La commande `stpkg` a besoin des executables `egrep` (ou `grep` si indisponible),
 `sponge` et `jq`. Il faut donc les installer ou les recompiler sur votre machine
 (`apt install moreutils jq grep`).
 
-> Il faut avoir utiliser le script `stpkg` et bien mettre les variables
-  `STPKG_BASE` et `STPKG_INSTALL` dans votre bashrc pour que `stpkg` fonctionne.
-
-Après avoir utilisé `stpkg --install`, vous pouvez placer le script `stpkg`
+### Utilisation basique
+Après avoir utilisé `stpkg -install`, vous pouvez placer le script `stpkg`
 dans votre path ou créer un alias pour l'exécuter facilement.
 
 Les commandes de `stpkg` :
-- `stpkg --install [dossier d'installation]`
+- `stpkg -install [-sshfs user@server -local mnt_local] [folder]`
 - `stpkg update`
 - `stpkg list [-e -p -np] [regex bash]`
 - `stpkg add <pack>`
 - `stpkg del <pack>`
+- `stpkg pack [-t token] [name] <folder>`
+
+> Au moment de l'installation `stpkg` a créé un fichier `~/.config/stpkg.sh`
+  qui sera sourcé à chaque lancement de `stpkg`. Il contient les variables
+  utilisées, vous pouvez les modifier selon vos envies.
+
+### Comment utiliser stpkg sur perso
+
+**TL;DR** sshfs à la rescousse.
+
+**Les vrais explications :** au moment de l'installation de `stpkg` on va
+utiliser les options `-sshfs <ssh address> -local <point de montage locale>`.
+Veillez noter que si vous utilisez l'option `-sshfs`, l'option `folder`
+pointera sur un dossier *sur perso*.
diff --git a/generate.sh b/generate.sh
deleted file mode 100755
index a24981e..0000000
--- a/generate.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-echo -n "{\"homeserver_url\":\"https://matrix.org\",\"packs\":[" > index.json
-first=""
-for f in packs/*/*.json
-do
-  echo -n "$first" >> index.json
-  echo -n "\"matrix-stickers/$f\"" >> index.json
-  first=","
-done
-echo -n "]}" >> index.json
diff --git a/matrixpack.sh b/matrixpack.sh
deleted file mode 100755
index 84add5f..0000000
--- a/matrixpack.sh
+++ /dev/null
@@ -1,165 +0,0 @@
-#!/bin/bash
-# Usage
-# matrixpack token homeserver directory...
-#
-# Pack name is the directory name
-# Sticker name is the file name
-# /!\ Token is a sensitive information
-
-# UTILITY FUNCTIONS
-function require {
-  hash $1 2>/dev/null || {
-    echo >&2 "Error: '$1' is required, but was not found."; exit 1;
-  }
-}
-
-function slugify () {
-    echo "$1" | iconv -c -t ascii//TRANSLIT | sed -E 's/[~^]+//g' | sed -E 's/[^a-zA-Z0-9]+/-/g' | sed -E 's/^-+|-+$//g' | tr A-Z a-z
-}
-
-# Display usage funtion
-display_usage (){
-    echo -e "\nUsage : ./matrixpack.sh token homeserver directory\n"
-}
-
-# Erase http:// or https:// if added in the homeserver
-slug_homeserver() {
-    echo "$1" | iconv -c -t ascii//TRANSLIT | sed -E 's/^http:\/\/|^https:\/\///g' | sed -E 's/^-+|-+$//g'
-}
-
-# COMMON REQUIRED BINARIES
-require convert
-require montage
-require identify
-require python
-require curl
-require sed
-require tr
-
-# Checking params
-if test $# -lt 3 ; then
-  echo 1>&2 "$0:FATAL: invalid argument number (expected 3)"
-  display_usage
-  exit 1
-fi
-
-# Setting variables
-token=$1
-homeserver=$(slug_homeserver $2)
-
-# Checking if the homeserver exist.
-# If the homeserver does not exist, the file headers is not created
-curl "https://$homeserver" -I -o headers -s
-if test -f "headers"; then
-    rm headers
-else
-    echo 1>&2 "$0:FATAL: The homeserver \"$2\" is incorrect."
-    exit 1
-fi
-
-# Checking if the token exist.
-# Save the error value on file "headers" and
-# evaluate it to verify the token
-curl -s -X POST  "https://$homeserver/_matrix/media/r0/upload?access_token=$token" | python3 -c "import sys, json; print(json.load(sys.stdin)['errcode'])" >> headers
-while read line; do
-    if [[ ($line == "M_UNKNOWN") ]]
-    then
-        rm headers
-    else if [[ ($line == "M_UNKNOWN_TOKEN") ]]
-    then
-        echo "$0:ERROR: The token provided is incorrect or does not exist in this homeserver"
-        rm headers
-        exit 1
-    else
-        echo "$0:ERROR: Not yet implemented error"
-        exit 1
-    fi
-    fi
-done < headers
-
-for i in "$@"
-do
-  if [ -d "$i" ]; then
-
-    # Changing directory to work directly in it
-    cd "$i"
-    dir=$(pwd)
-    packname=${dir##*/}
-    slug=$(slugify "$packname")
-
-    # Printing informations
-    echo -e "Creating sticker pack : \033[94;1m$packname\033[0m\nhomeserver=\033[94m$homeserver\033[0m\noutput=\033[94m$slug\033[0m"
-
-    # Making result folder
-    if ! [ -d $slug ]; then mkdir $slug; fi
-    if ! [ -d "$slug/tmp" ]; then mkdir "$slug/tmp"; fi
-    echo -n "{\"title\":\"$packname\",\"id\":\"$slug\",\"stickers\":[" > "$slug/$slug.json"
-
-    first=""
-    for f in *
-    do
-      # Ignore folders
-      if [ -f "$f" ]; then
-
-        # Resizing large images
-        width=$(identify -format "%w" "$f"[0])> /dev/null
-        height=$(identify -format "%h" "$f"[0])> /dev/null
-        if [ $width -gt 256 ]; then
-          width="256";
-        fi
-        if [ $height -gt 256 ]; then
-          height="256";
-        fi
-
-        echo -n "$f : "
-        type="png"
-        opts="-type TrueColor PNG32:"
-
-        # Gif
-        if [[ "$f" == *.gif ]]; then
-          type="gif"
-          opts=""
-        fi
-
-        # Erase the extension of the image
-        sticker_name=$(echo "$f" | cut -f 1 -d '.')
-
-        # Trim, resize and remove indexed palette from image
-        echo -n "trimming and resizing"
-        convert "$f" -bordercolor none -border 1 "$slug/tmp/$f.$type"
-        echo -n "."
-        convert "$slug/tmp/$f.$type" -trim +repage "$slug/tmp/$f.$type"
-        echo -n "."
-        convert -background none -gravity center "$slug/tmp/$f.$type" -resize "${width}x$height" $opts"$slug/tmp/$f.$type"
-        echo -ne ". \033[92mdone\033[0m! "
-
-        # First item in array
-        echo -n "$first" >> "$slug/$slug.json"
-
-        # Uploading image
-        echo -n "uploading."
-        mxc=$(curl -s -X POST -H "Content-Type: image/$type" --data-binary "@$slug/tmp/$f.$type" "https://$homeserver/_matrix/media/r0/upload?access_token=$token" | python -c "import sys, json; print(json.load(sys.stdin)['content_uri'])")
-        echo -n "."
-
-        # Calculating 128x128> format
-        convert "$slug/tmp/$f.$type" -resize "128x128" "$slug/tmp/size"
-        width=$(identify -format "%w" "$slug/tmp/size"[0])> /dev/null
-        height=$(identify -format "%h" "$slug/tmp/size"[0])> /dev/null
-
-        # Appending to json
-        echo -n "{\"body\":\"$sticker_name\",\"info\":{\"mimetype\":\"image/$type\",\"h\":$height,\"w\":$width,\"thumbnail_url\":\"$mxc\"},\"msgtype\":\"m.sticker\",\"url\":\"$mxc\",\"id\":\"$packname-$sticker_name\"}" >> "$slug/$slug.json"
-        first=","
-        echo -e ". \033[92msuccess\033[0m!"
-      fi
-    done
-
-    rm "$slug/tmp/size"
-    montage "$slug/tmp/*"[0] -background none "$slug/preview.png"
-    rm -r "$slug/tmp"
-    echo -ne "# $packname  \n![Preview of $packname](preview.png)" > "$slug/README.md"
-    echo -n "]}" >> "$slug/$slug.json"
-    cd - > /dev/null
-    echo -e "\033[92;1mPack successfully created!\n\033[0mCheck \033[94;1m$dir/$slug \033[0mfor output"
-
-  fi
-done
diff --git a/stpkg b/stpkg
index 34e0cd9..fb66196 100755
--- a/stpkg
+++ b/stpkg
@@ -1,12 +1,9 @@
 #!/bin/bash
 
+STPKG_CONF_FILE=~/config/stpkg.sh
 BASE_DIR="$PWD"
 DISPLAY_DEPS_NOTES="yes"
 
-# Home server
-STPKG_HOMESERV=${STPKG_HOMESERV:="matrix.org"}
-STPKG_HOMESERV=`echo "$STPKG_HOMESERV" | iconv -c -t ascii//TRANSLIT | sed -e 's/^http:\/\/|^https:\/\///g' -e 's/^-+|-+$//g'`
-
 if [ "x$STPKG_COLORS" = "x" ]; then
     STPKG_COLORS="yes"
     error() { __red    "$*\n" >/dev/stderr; }
@@ -31,12 +28,19 @@ else
     alias __bold=echo
 fi
 
+# Source conf file, may have the sshfs hook
+[ -f $STPKG_CONF_FILE ] && source $STPKG_CONF_FILE
+
 if [ "x$STPKG_NO_MSG" = "xyes" ]; then
     error() { return 0; }
     warn()  { return 0; }
     info()  { return 0; }
 fi
 
+# Home server
+STPKG_HOMESERV=${STPKG_HOMESERV:="matrix.org"}
+STPKG_HOMESERV=`echo "$STPKG_HOMESERV" | iconv -c -t ascii//TRANSLIT | sed -e 's/^http:\/\/|^https:\/\///g' -e 's/^-+|-+$//g'`
+
 ########################
 # Some basic functions #
 ########################
@@ -52,7 +56,7 @@ alias exit=__exit
 usage() {
 cat << EOF
 `__bold $0 usage:`
-    $0 --install [install path]
+    $0 -install [-sshfs username@server -local mnt_point] [install path]
     $0 update
     $0 list [-p -e -np] [bash regex]
     $0 add <pack>
@@ -74,7 +78,7 @@ cat << EOF
     STPKG_HOMESERV [homeserv]    The Matrix home server. ['iiens.net']
 
 `__bold Notes:`
-    The 'stpkg --install [path]' must be called only once. The default install
+    The 'stpkg -install [path]' must be called only once. The default install
     path is ~/html/stickerpicker. This command will give you a STPKG_INSTALL
     and a STPKG_BASE env that you must put in your bashrc for the rest of the
     stpkg commands to work.
@@ -130,15 +134,60 @@ require sponge
 require ls
 require find
 require jq
+require chmod
 
 ################################
 # The special install function #
 ################################
 
 __install() {
-    # Set install dir
-    local STPKG_INSTALL=$1
-    STPKG_INSTALL=${STPKG_INSTALL:="~/html/stickerpicker/"}
+    # Parse options
+    local PARSE_FLAGS=1
+    while [ $PARSE_FLAGS -eq 1 ]; do
+        case "$1" in
+            -sshfs)
+                local SSHFS="$2"
+                shift 2
+                ;;
+            -local)
+                local MNT="$2"
+                shift 2
+                ;;
+            *)
+                PARSE_FLAGS=0
+                ;;
+        esac
+    done
+
+    # Create the ~/config/stpkg.sh
+    [ ! -d ~/config ] && mkdir ~/config
+    echo "STPKG_BASE=$BASE_DIR"         >  $STPKG_CONF_FILE
+    echo "STPKG_HOMESERV='matrix.org'"  >> $STPKG_CONF_FILE
+    echo "STPKG_TOKEN=''"               >> $STPKG_CONF_FILE
+    chmod 00600 $STPKG_CONF_FILE
+
+    # Set install dir. Oh boi, tricky things going around here because we
+    # handle the sshfs ourself.
+    if [ ! "x$SSHFS" = "x" ]; then
+        [ "x$MNT" = "x" ] && die "You must specify a mount point with '-local /mount/pount' when using the '-sshfs' option"
+        local STPKG_INSTALL=$1
+        STPKG_INSTALL=$MNT${STPKG_INSTALL:="/html/stickerpicker/"}
+
+        # The sshfs hook
+        echo "STPKG_INSTALL=$STPKG_INSTALL"                                                             >> $STPKG_CONF_FILE
+        echo "[ ! -d \"$MNT\" ] && mkdir -p \"$MNT\" || die 'Failed to recreate mount point'"           >> $STPKG_CONF_FILE
+        echo "[ ! -d \"\$STPKG_INSTALL\" ] && sshfs $SSHFS:~/ $MNT"                                     >> $STPKG_CONF_FILE
+        echo "[ ! -d \"\$STPKG_INSTALL\" ] && die 'Failed to mount $SSHFS:~/ to $MNT, sshfs problems?'" >> $STPKG_CONF_FILE
+
+        # Do the sshfs hook
+        sshfs $SSHFS:~/ $MNT
+    else
+        local STPKG_INSTALL=$1
+        STPKG_INSTALL=${STPKG_INSTALL:="~/html/stickerpicker/"}
+        echo "STPKG_INSTALL=$STPKG_INSTALL" >> $STPKG_CONF_FILE
+    fi
+
+    # Check install dir
     [ -d "$STPKG_INSTALL" ] \
         && die "Folder '$STPKG_INSTALL' already exists." \
                "If you already installed the sticker picker you can use '$0 update'"
@@ -153,14 +202,9 @@ __install() {
 
     default_index > $STPKG_INSTALL/web/packs/index.json || die "Failed to create default index.json file"
 
-    # Needed ENV for future use
-    local STPKG_BASE=$BASE_DIR
-    info 'Installation done successfully, you may copy the "stpkg" file into your path or create an alias.'
-    info 'You may add the following lines in your bashrc file:'
-    echo "export STPKG_INSTALL='$STPKG_INSTALL'"
-    echo "export STPKG_BASE='$STPKG_BASE'"
+    info "You may edit the $STPKG_CONF_FILE to setup your home server and token"
 }
-if [ "x$1" = "x--install" ]; then
+if [ "x$1" = "x-install" ]; then
     [ "x$STPKG_NO_MSG" = "xyes" ] \
         && echo "!!! STPKG_NO_MSG is turn on, you won't see what's going on during the install"
     shift
-- 
GitLab