#!/bin/bash

# Generate random codes
# Syntax: generate_codes  
function generate_codes() {
  chars="abcdefghijklmnopqrstywxz1234567890ABCDEFHIJKLMNOPQRSTYWXZ@/"
  long_code="${1}"
  for i in {1} ; do
    echo -n "${chars:RANDOM%${#chars}:1}"
  done
}

# Function to crypt pass on config file
# Syntax: encrypt_kstools <password>
function encrypt_kstools() {
  raw_pass="${1}"
  characters_pass_raw=$(echo ${raw_pass} | wc -m)
  characters_pass=$(expr ${characters_pass_raw} - 1)
  total_characters=0
  mkdir -p ${HOME}/.ks-tools/
  rm -rf ${HOME}/.ks-tools/.seq-codes
  while [ ${total_characters} -le ${characters_pass} ] ; do
    num_gen=$(echo -n ${RANDOM} | cut -c1)
    echo -n ${num_gen} >> ${HOME}/.ks-tools/.seq-codes
    total_characters=$(expr ${total_characters} + 1)
  done
  characters_seq_raw=$(cat ${HOME}/.ks-tools/.seq-codes 2> /dev/null | wc -m)
  characters_seq=$(expr ${characters_seq_raw} - 1)
  total_characters=1
  encrypted_pass=""
  while [ ${total_characters} -le ${characters_pass} ] ; do
    num_seq_read=$(cat ${HOME}/.ks-tools/.seq-codes 2> /dev/null | cut -c${total_characters})
    character=$(echo ${raw_pass} | cut -c${total_characters})
    repeat_seq=0
    while [ ${repeat_seq} -lt ${num_seq_read} ] ; do
      code_gen=$(generate_codes)
      encrypted_pass="${encrypted_pass}${code_gen}"
      repeat_seq=$(expr ${repeat_seq} + 1)
    done
    encrypted_pass="${encrypted_pass}${character}"
    total_characters=$(expr ${total_characters} + 1)
  done
  code_gen=$(generate_codes)
  encrypted_pass="${encrypted_pass}${code_gen}"
  echo ${encrypted_pass}
}

# Function to decrypt pass on config file
# Syntax: decrypt_kstools <password>
function decrypt_kstools() {
  raw_pass_encrypted="${1}"
  total_characters=1
  codes_seq=$(cat ${HOME}/.ks-tools/.seq-codes 2> /dev/null)
  num_codes_seq=$(cat ${HOME}/.ks-tools/.seq-codes 2> /dev/null | wc -m)
  pass_decrypt=""
  total_characters=1
  pos_codes_pass=0
  while [ ${total_characters} -lt ${num_codes_seq} ] ; do
    pos_codes=$(echo ${codes_seq} | cut -c${total_characters})
    pos_codes_pass=$(expr ${pos_codes_pass} + ${pos_codes} + 1)
    pos_pass=$(expr ${raw_pass_encrypted} | cut -c${pos_codes_pass})
    pass_decrypt="${pass_decrypt}${pos_pass}"
    total_characters=$(expr ${total_characters} + 1)
  done
  echo ${pass_decrypt}
}

echo ""
echo " * Load functions: source $0"
echo ""
echo " + Usage:"
echo ""
echo "     encrypt_kstools <password>"
echo "     decrypt_kstools <password_encrypted>"
echo ""
