#!/bin/bash
DIRECTORY="$(readlink -f "$(dirname "$0")")"

function error {
  echo -e "\e[91m$1\e[39m"
  exit 1
}

#for text_editor() and script_name() functions
source "${DIRECTORY}/api" || error "failed to source ${DIRECTORY}/api"

#you can specify a preexisting app with variable 1
if [ ! -z "$1" ];then
  name="$1"
  step=2
  editing=yes
else
  name=''
  step=1
fi

#Sets the height of all dialog windows
windowheight=400

#start on this step:
#step=3
#start with this app name:
#name='Email Checker'

while true;do
  case $step in
    1) #STEP 1: introduction
      echo "Welcome to the Create App wizard!

With a few simple steps, your project can take advantage of Pi-Apps"\'" features and be displayed in the application list.
This wizard will save your work as you go." | yad --text-info --fontname=12 --wrap --show-uri \
        --image="${DIRECTORY}/icons/in-progress.png" --image-on-top \
        --text="<a href="\""https://github.com/Botspot/pi-apps/wiki/Creating-an-app"\"">READ THIS TUTORIAL FIRST!!</a>" \
        --title="Create App Wizard" --window-icon="${DIRECTORY}/icons/logo.png" --center --width=310 --height=$((windowheight-100)) \
        --button=Cancel!"${DIRECTORY}/icons/exit.png":1 \
        --button=Next!"${DIRECTORY}/icons/forward.png":0 || exit 0
      step=$((step+1))
      ;;
    2) #STEP 2: fill in initial values
      
      if [ ! -z "$name" ];then
        namelocked='yes'
        echo 'name field is already filled. Making it read-only.'
      fi
      
      if [ -f "${DIRECTORY}/apps/${name}/icon-64.png" ];then
        iconfield="--field=Icon::RO"
        iconpath="apps/${name}/icon-64.png"
      else
        iconfield="--field=Icon::FL"
        iconpath="${HOME}/bla"
      fi
      
      #if install script already exists, grey out compatibility line
      compatibilityentry="--field=Compatibility::CB"
      compatibilitypreset="64bit and 32bit!32bit only!64bit only"
      if [ ! -z "$name" ];then
      #if chosen app already has scripts, set cpu architecture compatibility and grey it out.
      compatibilityentry="--field=Compatibility::RO"
        if [ "$(script_name "$name")" == 'install' ] || [ "$(script_name "$name")" == 'install-32 install-64' ];then
          compatibilitypreset="64bit and 32bit"
        elif [ "$(script_name "$name")" == 'install-32' ];then
          compatibilitypreset="32bit only"
        elif [ "$(script_name "$name")" == 'install-64' ];then
          compatibilitypreset="64bit only"
        else
          #otherwise if app contains no install scripts, make Compatibility field editable.
          compatibilityentry="--field=Compatibility::CB"
        fi
      fi
      
      output="$(yad --form \
        --title="Create App: Step $step" --window-icon="${DIRECTORY}/icons/logo.png" --center --width=310 --height=$((windowheight+200)) \
        --text="Step ${step}: enter some information. The name field is mandatory." \
        --field="Name of app:$([ ! -z "$namelocked" ]&&echo ':RO')"  "$name" \
        "$iconfield" "$iconpath" \
        --field="Website:" "$(cat "${DIRECTORY}/apps/${name}/website" 2>/dev/null || echo '')" \
        "$compatibilityentry" "$compatibilitypreset" \
        --field="Description:":TXT "$(cat "${DIRECTORY}/apps/${name}/description" || cat "${DIRECTORY}/apps/template/description")" \
        --field="Credits:":TXT "$(cat "${DIRECTORY}/apps/${name}/credits" || cat "${DIRECTORY}/apps/template/credits")" \
        $([ ! -z $editing ]&&echo "--button=Save!${DIRECTORY}/icons/save.png:4") \
        --button=Previous!"${DIRECTORY}/icons/back.png":2 \
        --button=Next!"${DIRECTORY}/icons/forward.png":0 \
        2>/dev/null)"
      button=$? #get exit code to determine which button was pressed
      
      echo "$button"
      echo "Output: ${output}EOO"
      output="$(echo "$output" | tr '|' '\n' )"
      
      # if ------ next -- or -------- save ----- was clicked
      if [ $button == 0 ] || [ $button == 4 ];then
        name="$(echo "$output" | sed -n '1p')"
        icon="$(echo "$output" | sed -n '2p')"
        website="$(echo "$output" | sed -n '3p')"
        compatibility="$(echo "$output" | sed -n '4p')"
        description="$(echo -e "$(echo "$output" | sed -n '5p')")"
        credits="$(echo -e "$(echo "$output" | sed -n '6p')")"
        
        
        if [ -z "$(script_name "$name")" ];then
          #if app contains no install scripts, then parse yad output
          #convert compatibility var into machine-readable
          if [ "$compatibility" == "64bit and 32bit" ];then
            compatibility='install-32 install-64'
          elif [ "$compatibility" == "64bit and 32bit" ];then
            compatibility='install'
          elif [ "$compatibility" == "32bit only" ];then
            compatibility='install-32'
          elif [ "$compatibility" == "64bit only" ];then
            compatibility='install-64'
          fi
        else #app contains install scripts, so ignore yad window's setting (it was greyed out anyway) and set compatibility to whatever it was already.
          compatibility="$(script_name "$name")"
        fi
        
        #name field must be populated
        if [ ! -z "$name" ];then
          #check if name is a duplicate
          if [ -z "$(ls "${DIRECTORY}/apps" | grep -x "$name")" ] || [ ! -z $namelocked ];then
            #create app folder
            mkdir -p "${DIRECTORY}/apps/${name}" || error "failed to create ${DIRECTORY}/apps/${name}!"
            namelocked='yes'
            
            #if website field is populated
            if [ ! -z "$website" ];then
              echo "$website" > "${DIRECTORY}/apps/${name}/website"
              echo "Created ${DIRECTORY}/apps/${name}/website"
            fi
            
            #if icon field is populated and if file exists
            if [ ! -z "$icon" ] && [ -f "$icon" ];then
              #ensure imagemagick is installed
              if [ ! -f /usr/bin/convert ];then
                yad --text="To resize the images, imagemagick must be installed.
Install now?" \
                --text-align=center --center --title='Quick question' --window-icon="${DIRECTORY}/icons/logo.png" \
                --button=No!"${DIRECTORY}/icons/exit.png":1 --button=Yes!"${DIRECTORY}/icons/check.png":0
                button=$?
                if [ $button == 0 ];then
                  sudo apt install -y --no-install-recommends imagemagick || icon=''
                else
                  #clear the icon var to disable the icon
                  icon=''
                fi
              fi
              #if icon var not empty
              if [ ! -z "$icon" ];then
                #scale it to 24x24
                convert "$icon" -resize 24x24 "${DIRECTORY}/apps/${name}/icon-24.png"
                if [ -f "${DIRECTORY}/apps/${name}/icon-24.png" ];then
                  echo "Created ${DIRECTORY}/apps/${name}/icon-24.png from $icon"
                else
                  echo "Failed to create ${DIRECTORY}/apps/${name}/icon-24.png from $icon! Most likely you need to install imagemagick."
                fi
                #scale it to 64x64
                convert "$icon" -resize 64x64 "${DIRECTORY}/apps/${name}/icon-64.png"
                if [ -f "${DIRECTORY}/apps/${name}/icon-64.png" ];then
                  echo "Created ${DIRECTORY}/apps/${name}/icon-64.png from $icon"
                else
                  echo "Failed to create ${DIRECTORY}/apps/${name}/icon-64.png from $icon! Most likely you need to install imagemagick."
                fi
              fi
            fi
            
            #if description field is populated
            if [ ! -z "$description" ];then
              echo "$description" > "${DIRECTORY}/apps/${name}/description"
              echo "Created ${DIRECTORY}/apps/${name}/description"
            fi
            
            #if credits field is populated
            if [ ! -z "$credits" ];then
              echo "$credits" > "${DIRECTORY}/apps/${name}/credits"
              echo "Created ${DIRECTORY}/apps/${name}/credits"
            elif [ -z "$credits" ] && [ -f "${DIRECTORY}/apps/${name}/credits" ] ;then
              #clear credits if the user wanted them cleared.
              echo '' > "${DIRECTORY}/apps/${name}/credits"
            fi
            
            step=$((step+1))
          else
            echo 'That app name already exists!'
            yad --title="Error" --window-icon="${DIRECTORY}/icons/logo.png" --center \
            --text="That app name already exists!
Do you want to edit ${name}?" --timeout=10 \
            --button="Edit ${name}!${DIRECTORY}/icons/edit.png":0 --button="Oops, go back!${DIRECTORY}/icons/back.png":1 || name=''
          fi
        else
          echo 'Name of app may not be left blank!'
          yad --title="Error" --window-icon="${DIRECTORY}/icons/logo.png" --center \
            --text="Name of app may not be left blank!" --timeout=10 \
            --button=OK:0
        fi
        
        #if Save was clicked then exit now
        if [ $button == 4 ];then
          exit 0
        fi
      elif [ $button == 2 ];then
        #previous - don't save changes
        step=$((step-1))
      else
        #like clicking the X or something 
        exit 0
      fi
      
      ;;
    3) #STEP 3: create install script
      
      #ask if two install scripts are necessary, of if both architectures can share 1 script
      if [ "$compatibility" == "install-32 install-64" ] && [ -z "$(script_name "$name")" ];then
        echo "In the previous page, you said this app is compatible with 64bit and 32bit.
Do you want two install scripts, one for 32bit and the other for 64bit?
Or do you want one combined install script?" | yad --text-info --fontname=12 --wrap --show-uri \
          --title="Create App: Step $step" --window-icon="${DIRECTORY}/icons/logo.png" --center --width=310 --height=$windowheight \
          --button="Previous!${DIRECTORY}/icons/back.png":1 \
          --button='2 scripts':2 \
          --button='1 script':0
        
        button=$? #get exit code to determine which button was pressed
        
        if [ $button == 1 ];then
          #button clicked: Previous
          step=$((step-1))
          continue #back to top of while loop
        elif [ ! $button == 0 ] && [ ! $button == 2 ];then
          #Window manager X, or escape, or terminated
          exit 0
        elif [ $button == 0 ];then
          #button clicked: '1 script'
          compatibility=install #change compatibility var from 'install-32 install-64' to 'install', to show that only an install script will be created
        elif [ $button == 2 ];then
          #button clicked: '2 scripts'
          true #do nothing, as $compatibility already contains "install-32 install-64"
        fi
      fi #end of asking for 1 script or 2 scripts
      
      #copy right files from template, based on $compatibility variable
      if [ "$compatibility" == "install-32" ];then
        cp -n "${DIRECTORY}/apps/template/install" "${DIRECTORY}/apps/${name}/install-32"
        
      elif [ "$compatibility" == "install-64" ];then
        cp -n "${DIRECTORY}/apps/template/install" "${DIRECTORY}/apps/${name}/install-64"
        
      elif [ "$compatibility" == "install" ];then
        cp -n "${DIRECTORY}/apps/template/install" "${DIRECTORY}/apps/${name}/install"
        
      elif [ "$compatibility" == "install-32 install-64" ];then
        cp -n "${DIRECTORY}/apps/template/install" "${DIRECTORY}/apps/${name}/install-32"
        cp -n "${DIRECTORY}/apps/template/install" "${DIRECTORY}/apps/${name}/install-64"
      fi
      
      #open the correct file in text editor
      if [ "$compatibility" == "install-32" ];then
        text_editor "${DIRECTORY}/apps/${name}/install-32" &
        
      elif [ "$compatibility" == "install-64" ];then
        text_editor "${DIRECTORY}/apps/${name}/install-64" &
        
      elif [ "$compatibility" == "install-32 install-64" ];then
        text_editor "${DIRECTORY}/apps/${name}/install-64" &
        text_editor "${DIRECTORY}/apps/${name}/install-32" &
        
      elif [ "$compatibility" == "install" ];then
        text_editor "${DIRECTORY}/apps/${name}/install" &
      fi
      
      #install shellcheck if not installed
      command -v shellcheck >/dev/null || sudo apt install -y shellcheck
      
      #if creating 2 scripts
      if [ "$compatibility" == 'install-32 install-64' ];then
        
        yad --form --on-top \
          --title="Create App: Step $step" --window-icon="${DIRECTORY}/icons/logo.png" --center --width=310 --height=$windowheight \
          --text="Now it's time to make your install-32 and install-64 scripts.

One of these scripts will be executed when somebody clicks your app's Install button.
Two text editors should have openened and you can create your scripts.
Need help? <a href="\""https://github.com/Botspot/pi-apps/wiki/Creating-an-app"\"">Read the tutorial!</a>
Still need help? Botspot can try to help you if you <a href="\""https://github.com/Botspot/pi-apps/issues/new/choose"\"">open in issue.</a>" \
          --field="Run install-32 script":FBTN "${DIRECTORY}/etc/terminal-run "\""cd $HOME;$'${DIRECTORY}/apps/${name}/install-32';echo 'Closing in 10 seconds.';sleep 10"\"" "\""Running install-32 script of $name"\""" \
          --field="Shellcheck install-32"!!'Having problems? This utility helps you locate syntax errors.':FBTN "${DIRECTORY}/etc/terminal-run "\""shellcheck $'${DIRECTORY}/apps/${name}/install-32';echo 'Press Enter to exit.';read enter"\"" "\""Shellcheck"\""" \
          --field="Run install-64 script":FBTN "${DIRECTORY}/etc/terminal-run "\""cd $HOME;$'${DIRECTORY}/apps/${name}/install-64';echo 'Closing in 10 seconds.';sleep 10"\"" "\""Running install-64 script of $name"\""" \
          --field="Shellcheck install-64"!!'Having problems? This utility locates syntax errors.':FBTN "${DIRECTORY}/etc/terminal-run "\""shellcheck $'${DIRECTORY}/apps/${name}/install-64';echo 'Press Enter to exit.';read enter"\"" "\""Shellcheck"\""" \
          --button=Previous!"${DIRECTORY}/icons/back.png":2 \
          --button=Next!"${DIRECTORY}/icons/forward.png":0 \
          2>/dev/null
        button=$? #get exit code to determine which button was pressed
        
      else #if creating 1 script
        yad --form --on-top \
          --title="Create App: Step $step" --window-icon="${DIRECTORY}/icons/logo.png" --center --width=310 --height=$windowheight \
          --text="Now it's time to make your ${compatibility} script. This will be executed anytime somebody clicks the Install button.

A text editor should have openened and you can create your install script.
Need help? <a href="\""https://github.com/Botspot/pi-apps/wiki/Creating-an-app"\"">Read the tutorial!</a>
Still need help? Botspot can try to help you if you <a href="\""https://github.com/Botspot/pi-apps/issues/new/choose"\"">open in issue.</a>" \
          --field="Run script":FBTN "${DIRECTORY}/etc/terminal-run "\""cd $HOME;$'${DIRECTORY}/apps/${name}/${compatibility}';echo 'Closing in 10 seconds.';sleep 10"\"" "\""Running ${compatibility} script of $name"\""" \
          --field="Shellcheck"!!'Having problems? This utility locates syntax errors.':FBTN "${DIRECTORY}/etc/terminal-run "\""shellcheck $'${DIRECTORY}/apps/${name}/${compatibility}';echo 'Press Enter to exit.';read enter"\"" "\""Shellcheck"\""" \
          --button=Previous!"${DIRECTORY}/icons/back.png":2 \
          --button=Next!"${DIRECTORY}/icons/forward.png":0 \
          2>/dev/null
        button=$? #get exit code to determine which button was pressed
      fi
      
      if [ $button == 0 ];then
        #next
        step=$((step+1))
      elif [ $button == 2 ];then
        #previous
        step=$((step-1))
      else
        #like clicking the X or something 
        exit 0
      fi
      ;;
    4) #STEP 4: create uninstall script
      cp -n "${DIRECTORY}/apps/template/uninstall" "${DIRECTORY}/apps/${name}/uninstall"
      
      text_editor "${DIRECTORY}/apps/${name}/uninstall" &
      
      #install shellcheck if not installed
      command -v shellcheck >/dev/null || sudo apt install -y shellcheck
      
      output="$(yad --form --on-top \
        --title="Create App: Step $step" --window-icon="${DIRECTORY}/icons/logo.png" --center --width=310 --height=$windowheight \
        --text='Now it'\''s time to make your uninstall script. This will be executed anytime somebody clicks the Uninstall button.
A text editor should have openened... Never mind, you know what to do.' \
        --field="Run script":FBTN "${DIRECTORY}/etc/terminal-run "\""cd $HOME;$'${DIRECTORY}/apps/${name}/uninstall';echo 'Closing in 10 seconds.';sleep 10"\"" "\""Running uninstall script of $name"\""" \
        --field="Shellcheck"!!'Having problems? This utility helps you locate syntax errors.':FBTN "${DIRECTORY}/etc/terminal-run "\""shellcheck $'${DIRECTORY}/apps/${name}/uninstall';echo 'Press Enter to exit.';read enter"\"" "\""Shellcheck"\""" \
        --button=Previous!"${DIRECTORY}/icons/back.png":2 \
        --button=Next!"${DIRECTORY}/icons/forward.png":0 \
        2>/dev/null)"
      button=$? #get exit code to determine which button was pressed
      
      if [ $button == 0 ];then
        #next
        step=$((step+1))
      elif [ $button == 2 ];then
        #previous
        step=$((step-1))
      else
        #like clicking the X or something 
        exit 0
      fi
      ;;
    5) #STEP 5: verify in app list
      LIST="${DIRECTORY}/icons/uninstalled.png
${DIRECTORY}/apps/${name}/icon-24.png
$name
"\("uninstalled"\)" $(echo "$(cat "${DIRECTORY}/apps/${name}/description" || echo "Description unavailable")" | head -n1)"
      
      echo -e "$LIST" | yad --list \
        --title="Create App: Step $step" --window-icon="${DIRECTORY}/icons/logo.png" --center --width=310 --height=$windowheight \
        --text='Make sure everything looks right.
Here'\''s what it will look like in the app list:' \
        --column=:IMG --column=:IMG --column=Name --column=tip:HD --tooltip-column=4 --no-headers \
        --button=Previous!"${DIRECTORY}/icons/back.png":2 \
        --button=Next!"${DIRECTORY}/icons/forward.png":0 \
        2>/dev/null
      button=$? #get exit code to determine which button was pressed
      
      if [ $button == 0 ];then
        step=$((step+1))
      elif [ $button == 2 ];then
        step=$((step-1))
      else
        #like clicking the X or something 
        exit 0
      fi
      ;;
    6) #STEP 6: verify in Details window
      
      text="$(echo "$(cat "${DIRECTORY}/apps/${name}/description" || echo "Description unavailable")" | head -n1)
Current status: uninstalled
Website: $(cat "${DIRECTORY}/apps/${name}/website" || echo "unavailable")
$(echo "$(cat "${DIRECTORY}/apps/${name}/description" || echo "Description unavailable")" | grep -v "$(echo "$(cat "${DIRECTORY}/apps/${name}/description" || echo "Description unavailable")" | head -n1)")"
      
      echo "$text" | yad --text-info --fontname=12 --wrap --show-uri \
        --title="Create App: Step $step" --window-icon="${DIRECTORY}/icons/logo.png" --center --width=700 --height=400 \
        --text='Make sure everything looks right.
Here'\''s a preview of the Details window:' \
        --image="${DIRECTORY}/apps/${name}/icon-64.png" --image-on-top \
        --button=Previous!"${DIRECTORY}/icons/back.png":2 \
        --button=Next!"${DIRECTORY}/icons/forward.png":0 \
        2>/dev/null
      button=$? #get exit code to determine which button was pressed
      
      if [ $button == 0 ];then
        step=$((step+1))
      elif [ $button == 2 ];then
        step=$((step-1))
      else
        #like clicking the X or something 
        exit 0
      fi
      ;;
    7) #STEP 7: all done
      echo "Done!
You app is located at ${DIRECTORY}/apps/${name}
To add your app to the Pi-Apps official repository, put that folder in a .ZIP file and open an issue for Botspot (the developer of Pi-Apps): https://github.com/Botspot/pi-apps/issues/new" | yad --text-info --fontname=12 --wrap --show-uri \
        --image="${DIRECTORY}/icons/in-progress.png" --image-on-top \
        --title="Create App Wizard" --window-icon="${DIRECTORY}/icons/logo.png" --center --width=310 --height=$windowheight \
        --button=Previous!"${DIRECTORY}/icons/back.png":0 \
        --button=Close!"${DIRECTORY}/icons/exit.png":1 || exit 0
      step=$((step-1))
      ;;
    *)
      error "Unknown step ${step}!"
      ;;
  esac
done
